Here is an example of what I want to do:
MessageBox.Show("Error line number "+CurrentLineNumber);
Current line number will be the line number in the source code of this piece of code.
How can I do that?
Here is an example of what I want to do:
MessageBox.Show("Error line number "+CurrentLineNumber);
Current line number will be the line number in the source code of this piece of code.
How can I do that?
I prefer one liners so:
In .NET 4.5 / C# 5, you can get the compiler to do this work for you, by writing a utility method that uses the new caller attributes:
This will display, for example:
There's also
[CallerFilePath]
which tells you the path of the original code file.This works for me:
Use the StackFrame.GetFileLineNumber method, for example:
See Scott Hanselman's Blog entry for more information.
[Edit: Added the following]
For those using .Net 4.5 or later, consider the CallerFilePath, CallerMethodName and CallerLineNumber attributes in the System.Runtime.CompilerServices namespace. For example:
The arguments must be
string
forCallerMemberName
andCallerFilePath
and anint
forCallerLineNumber
and must have a default value. Specifying these attributes on method parameters instructs the compiler to insert the appropriate value in the calling code at compile time, meaning it works through obfuscation. See Caller Information for more information.For those who need a .NET 4.0+ method solution:
How to call:
Output:
Change the Console.WriteLine format how you like!
If its in a try catch block use this.