Search code examples
c#functionprintingline

How to print function name without hard code string?


c language has macro like FILE/LINE to print file name and code line number

So how does C# language achieve same goal, is it possible to do, or require assembly packages?

Thanks a lot.


Solution

  • You can use StackFrame, i would be wary about doing this though, it will come at a performance cost and is likely to give you issues in release .

    Represents a stack trace, which is an ordered collection of one or more stack frames.

    var stackTrace = new StackTrace(0, true);
    var sf = stackTrace.GetFrame(0);
    Console.WriteLine("FileName: {0}", sf.GetFileName());
    Console.WriteLine("Line Number:{0} ",sf.GetFileLineNumber());
    Console.WriteLine("Function Name:{0}",sf.GetMethod ());