This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 4.5+

Obtaining Caller Information

When using the .NET framework version 4.5, it is possible to obtain information about the caller of a method without using a stack trace. This is achieved by decorating method parameters with one of three new caller information attributes.

Caller Attributes

It can be useful to obtain the details of the member that called the current method. This is particularly helpful when adding change notifications to properties in a class that implements INotifyPropertyChanged, or when developing code that performs logging or tracing functions.

Before the introduction of the .NET framework version 4.5, you could obtain a stack trace and examine the list of calls to determine the caller. .NET 4.5 makes the process easier with three new caller information attributes. These are defined in the CallerMemberNameAttribute, CallerLineNumberAttribute and CallerFilePathAttribute classes. They allow access to the caller's name, the line number of the call and the path to the file containing the caller respectively.

Each of the three attributes can be applied to a method parameter. To obtain the name or the file path of the caller you decorate a string parameter with the appropriate attribute. For line numbers the parameter must accept an integer. In each case you must create an optional parameter by including a default value. This allows callers to omit the three arguments and allow the information to be added automatically.

The three new attributes are part of the System.Runtime.CompilerServices namespace, so include the following using directive to simplify your code:

using System.Runtime.CompilerServices;

You can see an example in the Test method below. Here the method has three parameters, all with default values to make them optional and each decorated with one of the new attributes.

public static void Test(
    [CallerMemberName] string name = "",
    [CallerLineNumber] int line = 0,
    [CallerFilePath] string path = "")
    Console.WriteLine("Called by {0} line {1} in {2}", name, line, path);

If the above method is called from the Main method of a console application with no arguments provided, the output will be similar to that shown below:

Called by Main line 14 in c:\test\Program.cs


There is a limitation to the use of the caller attributes that makes it possible to disguise the caller. As we are using optional parameters, it is possible for the caller to provide a value. This is received by the method and used instead of the automatically added information.

For example, the following call to Test specifies the line number to the line argument, hiding the true line number.

Test(line: 99);

When executed, the output shows the provided line number.

Called by Main line 99 in c:\test\Program.cs
6 January 2013