Search code examples
c#visual-studio

How to include line number and file name Console.WriteLine output?


Is there a way to include line numbers and file name in C#'s Console.WriteLine function?

For example, on the line 115 of file "myClass.cs" I have the statement

Console.WriteLine("Hello world");

I would like the output to be:

[myClass.cs][115]:  Hello world 

Solution

  • If you're using C# 5, you can use caller information attributes to do this. For example:

    using System;
    using System.IO;
    using System.Runtime.CompilerServices;
    
    public class Test
    {
        static void Log(string message,
                        [CallerFilePath] string file = null,
                        [CallerLineNumber] int line = 0)
        {
            Console.WriteLine("{0} ({1}): {2}", Path.GetFileName(file), line, message);
        }
        
        static void Main()
        {
            Log("Hello, world");
            Log("This is the next line");
        }
    }
    

    Output:

    Test.cs (16): Hello, world
    Test.cs (17): This is the next line
    

    Before C# 5, you're stuck with execution-time stack checking, which is less reliable due to inlining, and relies on the information being present at execution time. (It might not in a release build, for example, whereas the above will still work.)