Over a million developers have joined DZone.

Caller Info Attributes in C# 5 Are a Framework-Agnostic Compiler Feature

DZone's Guide to

Caller Info Attributes in C# 5 Are a Framework-Agnostic Compiler Feature

· ·
Free Resource

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)

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.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}