Home > Backend Development > C++ > How Can I Get the Current Line Number in .NET?

How Can I Get the Current Line Number in .NET?

Patricia Arquette
Release: 2024-12-26 17:09:10
Original
730 people have browsed it

How Can I Get the Current Line Number in .NET?

Getting the Current Line Number in .NET

Determining the current line number in your code can be useful for debugging or displaying error messages. Here's how you can achieve it:

In .NET 4.5 / C# 5, you can use the compiler's built-in functionality. Define a utility method that leverages the new caller attributes:

using System.Runtime.CompilerServices;

static void SomeMethodSomewhere()
{
    ShowMessage("Boo");
}
...
static void ShowMessage(string message,
    [CallerLineNumber] int lineNumber = 0,
    [CallerMemberName] string caller = null)
{
     MessageBox.Show(message + " at line " + lineNumber + " (" + caller + ")");
}
Copy after login

When you call SomeMethodSomewhere(), it will display:

Boo at line 39 (SomeMethodSomewhere)
Copy after login

In addition, you can use [CallerFilePath] to retrieve the path of the original code file.

The above is the detailed content of How Can I Get the Current Line Number in .NET?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template