Software Architecture – System.Runtime.CompilerServices Namespace – Caller method info

September 30, 2012

In .Net 4.5, in System.Runtime.CompilerServices Namespace, 3 new classes are introduced which provide an option to be placed with optional parameter to get information about caller method.

As copied from msdn:

CallerFilePathAttribute
Allows you to obtain the full path of the source file that contains the caller. This is the file path at the time of compile.

CallerLineNumberAttribute

Allows you to obtain the line number in the source file at which the method is called.

CallerMemberNameAttribute

Allows you to obtain the method or property name of the caller to the method.

Tried it as below:

public static  void CheckDotNet2012NewFeature(
                [CallerMemberName] string callerMemberName = "",
                [CallerFilePath] string callerFilePath = "",
                [CallerLineNumber] int callerLineNumber = 0)
        {
            Console.WriteLine("Caller Info - method name: " + callerMemberName);
            Console.WriteLine("Caller Info - source file path: " + callerFilePath);
            Console.WriteLine("Caller Info - source line number: " + callerLineNumber);
        }

        static void Main(string[] args)
        {
            CheckDotNet2012NewFeature();
            Console.ReadLine();
        }

 

Output was as below:

Advertisements