Home >Backend Development >C++ >How Can I Get the Current Line Number in C# Code?
Retrieving the Current Line Number
In C#, determining the current line number in source code can be accomplished through techniques that vary depending on the version of the .NET framework and the language version being used.
Using Caller Attributes (.NET 4.5 / C# 5 and above)
In .NET 4.5 and later versions, C# 5 introduced the use of caller attributes, providing a convenient method to retrieve the line number and other information. To implement this approach:
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 + ")"); }
SomeMethodSomewhere();
Boo at line 39 (SomeMethodSomewhere)
Note: This method also provides access to the [CallerFilePath] attribute, which can be useful for obtaining the path of the original code file.
The above is the detailed content of How Can I Get the Current Line Number in C# Code?. For more information, please follow other related articles on the PHP Chinese website!