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
Patricia ArquetteOriginal
2024-12-26 17:09:10734browse

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 + ")");
}

When you call SomeMethodSomewhere(), it will display:

Boo at line 39 (SomeMethodSomewhere)

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!

Statement:
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