Sunday, December 22, 2013

Caller Information in C# 5.0

Getting Caller Information using Caller Info attributes is initially introduced with .NET Framework 4.5. It can be real handy if you want to write a module for tracing, debugging etc.

Following are the Caller Info Attributes which are defined in System.Runtime.CompilerServices namespace.

Let’s see a very simple example.
using System;
using System.Runtime.CompilerServices;
 
namespace CallerInfoDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            TraceMessage("Caller Info Attributes...");
        } 

        static void TraceMessage(string message = "",
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string sourceFilePath = "",
        [CallerLineNumber] int sourceLineNumber = 0)
        {
            Console.WriteLine("Message: " + message);
            Console.WriteLine("Member name: " + memberName);
            Console.WriteLine("Source file path: " + sourceFilePath);
            Console.WriteLine("Source line number: " + sourceLineNumber);
        }
    }
}
Please note the optional parameters which are marked with Caller Info Attributes in the TraceMessage method.

This will print the following output.
Picture1
Output
Please check the following post to get to know about a scenario where Caller Information can be used very effectively.
    INotifyPropertyChanged Without Hardcoding the Property Name

Download the sample from my SkyDrive.

 
Happy Coding.

Regards,
Jaliya