How do I get the current line number?

MonsterMMORPG picture MonsterMMORPG · Sep 24, 2012 · Viewed 77k times · Source

Here is an example of what I want to do:

MessageBox.Show("Error line number " + CurrentLineNumber);

In the code above the CurrentLineNumber, should be the line number in the source code of this piece of code.

How can I do that?

Answer

Marc Gravell picture Marc Gravell · Jan 2, 2013

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:

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

This will display, for example:

Boo at line 39 (SomeMethodSomewhere)

There's also [CallerFilePath] which tells you the path of the original code file.