Retrieving the Current Line Number in .NET
Obtaining the line number of the currently executing code can be useful for debugging and logging purposes. This article explores how to accomplish this task in .NET.
Using Caller Attributes
In .NET 4.5 / C# 5 and above, caller attributes provide a convenient way to retrieve line and member information:
[CallerLineNumber] int lineNumber = 0; [CallerMemberName] string caller = null; // ... MessageBox.Show(message + " at line " + lineNumber + " (" + caller + ")");
This will display the line number and method name of the calling code, such as:
Boo at line 39 (SomeMethodSomewhere)
Other Options
Prior to .NET 4.5, the following approach was commonly used:
StackTrace stackTrace = new StackTrace(true); int lineNumber = stackTrace.GetFrame(0).GetFileLineNumber(); string caller = stackTrace.GetFrame(0).GetMethod().Name;
However, this method required manual handling of indices and should not be used in favor of the preferred caller attributes.
The above is the detailed content of How to Get the Current Line Number in .NET?. For more information, please follow other related articles on the PHP Chinese website!