Caller info attributes in C# 5 are a compiler feature – they are framework agnostic

The new caller information attributes in C# 5 are excellent news for people tired of writing logging and diagnostic code or implementing INotifyPropertyChanged. You simply supply the correct attribute for the function parameters with default values and voilà Рyou get information about the caller for free. Consider the following code:

using System;
using System.Runtime.CompilerServices;

class Program
{
    static void SayMyName([CallerMemberName] string functionName = "",
                          [CallerFilePath] string filePath = "",
                          [CallerLineNumber] int lineNumber = 0)
    {
        Console.WriteLine("{0}:{1}({2})", filePath, functionName, lineNumber);
    }

    static void Main(string[] args)
    {
        SayMyName();
    }
}

The output of this simple program is:

c:\Users\Toni\Documents\Visual Studio 11\Projects\test_console\cstest\Program.cs:Main(15)

Excellent, we have the caller’s information for free. .NET 4.5 Framework introduced the above used attributes: CallerMemberNameAttribute, CallerFilePathAttribute and CallerLineNumberAttribute. They are defined in the System.Runtime.CompilerServices namespace. This means that if you are using Visual Studio 11 and you are targeting earlier framework, you do not have those types defined in mscorlib.dll. However, even though this might make you think that you are left in the dark, this is a compiler feature which means that these attributes are nothing but a magic keywords for the compiler. They themselves do nothing!

In fact, I have compiled the above program targeting .NET 2.0 Framework, the earliest target type available in Visual Studio 11. The trick is to add the right “magic” attributes and it will work since the compiler will interpret them correctly. The full source code is rather short and you can find it as a gist at github.

I based this idea on a similar “hack” for using async in projects targeting .NET 4 on the C#5 compiler: https://gist.github.com/1961087.

Last updated by at .