Print the source filename and linenumber in C#

Anders Hejlsberg presented new API for that in BUILD keynote:

Print current file name, method name and line number

private static void Log(string text,
                        [CallerFilePath] string file = "",
                        [CallerMemberName] string member = "",
                        [CallerLineNumber] int line = 0)
{
    Console.WriteLine("{0}_{1}({2}): {3}", Path.GetFileName(file), member, line, text);
}

Test:

Log(".NET rocks!");

Output:

Program.cs_Main(11): .NET rocks!

What’s going on here?

You define a method with optional parameters and decorate them with special attributes. If you call method without passing actual arguments (leave defaults) – the Framework populates them for you.

Leave a Comment