Look at Caller Info Feature in C# 4.5

In this blog, we will look into one of the new feature of C# 4.5 which gives details of the caller of a method. This feature is implemented using new compiler services in 4.5 and helps us to get caller method's name, its line number and file path. This feature helps us in logging and modifying method's logic based on its caller method. Let's create a sample C# console application targeting 4.5 framework as shown below:

Image-1.jpg

We will use CallerMemberName, CallerLineNumber and CallerFilePath attributes part of System.Runtime.CompilerServices namespace to get details of caller's method as shown below:

class Program

{

    static void Main(string[] args)

    {

        CallMe();

        MethodA();

        Console.ReadLine();

    }

    private static void MethodA()

    {

        CallMe();

    }

    public static void CallMe([CallerMemberName] string CallerName = "", [CallerLineNumber] int CalledFrom = 0, [CallerFilePath] string CallerFilePath = "")

    {

        if (CallerName == "MethodA")

        {

            //Your Logic based on Caller

        }

        Console.WriteLine("Called From: " + CallerName + " Method \r\nLine Number: " + CalledFrom.ToString() + "\r\nFile Path: " + CallerFilePath);

        Console.WriteLine();

    }

}

Run the application, it shows below output:

Image-2.jpg

These attributes can only be applied on optional parameters [having default values] and can be used on a method, event, property, constructor [returns “.ctor”], destructor [returns “Finalize”] etc.

By using this new feature, we can do logging for diagnostics, change method's behavior based on caller's name as well as in implementing the INotifyPropertyChanged interface when binding data

Next Recommended Reading C# 7.0 New Feature - Tuples In C# 7