Using Caller Info Attributes in .NET 4.5

Introduction

When developing complex .NET applications sometimes you need to find out the details about the caller of a method. .NET Framework 4.5 introduces what is known as Caller Info Attributes, a set of attributes that give you the details about a method caller. Caller info attributes can come in handy for tracing, debugging and diagnostic tools or utilities. This article examines what Caller Info Attributes are and how to use them in a .NET application.  

Overview of Caller Info Attributes

Caller Info Attributes are attributes provided by the .NET Framework (System.Runtime.CompilerServices) that give details about the caller of a method. The caller info attributes are applied to a method with the help of optional parameters. These parameters don’t take part in the method signature, as far as calling the method is concerned. They simply pass caller information to the code contained inside the method. Caller info attributes are available to C# as well as Visual Basic and are listed below:

Caller Info Attribute Description
CallerMemberName This attribute gives you the name of the caller as a string. For methods, the respective method names are returned whereas for constructors and finalizers strings “.ctor” and “Finalizer” are returned.
CallerFilePath This attribute gives you the path and file name of the source file that contains the caller.
CallerLineNumber This attribute gives you the line number in the source file at which the method is called.

A common use of these attributes will involve logging the information returned by these attributes to some log file or trace.

Using Caller Info Attributes

Now that you know what Caller Info Attributes are, let’s create a simple application that shows how they can be used. Consider the Windows Forms application shown below:

Windows Forms application

Windows Forms application

The above application consists of two Visual Studio projects – a Windows Forms project that contains a form as shown above and a Class Library project that contains a class called Employee. As you might have guessed the Windows Form accepts EmployeeID, FirstName and LastName and calls AddEmployee() method of the Class Library. Though the application doesn’t do any database INSERTs for the sake of illustrating Caller Info Attributes this setup is sufficient.

The Employee class that resides in the Class Library project is shown below:

public class Employee
{
    public Employee([CallerMemberName]string sourceMemberName = "",
                    [CallerFilePath]string sourceFilePath = "",
                    [CallerLineNumber]int sourceLineNo = 0)
    {
        Debug.WriteLine("Member Name : " + sourceMemberName);
        Debug.WriteLine("File Name : " + sourceFilePath);
        Debug.WriteLine("Line No. : " + sourceLineNo);
    }

    private int intEmployeeID;
    public int EmployeeID
    {
        get
        {
            return intEmployeeID;
        }
        set
        {
            intEmployeeID = value;
        }
    }

    private string strFirstName;
    public string FirstName
    {
        get
        {
            return strFirstName;
        }
        set
        {
            strFirstName = value;
        }
    }

    private string strLastName;
    public string LastName
    {
        get
        {
            return strLastName;
        }
        set
        {
            strLastName = value;
        }
    }

    public string AddEmployee([CallerMemberName]string sourceMemberName="",
                              [CallerFilePath]string sourceFilePath="",
                              [CallerLineNumber]int sourceLineNo=0)
    {
        Debug.WriteLine("Member Name : " + sourceMemberName);
        Debug.WriteLine("File Name : " + sourceFilePath);
        Debug.WriteLine("Line No. : " + sourceLineNo);
        //do database INSERT here
        return "Employee added successfully!";
    }

}

The Employee class is quite simple. It contains a constructor, a method named AddEmployee() and three properties, viz. EmployeeID, FirstName and LastName. The caller info attributes are used in the constructor and AddEmployee() method. Notice how the caller info attributes are used. To use any of the caller info attributes you need to declare optional parameters and then decorate them with the appropriate attributes. In the above example the code declares three optional parameters, viz. sourceMemberName, sourceFilePath and sourceLineNo. Note that sourceLineNo is an integer parameter since the [CallerLineNumber] attribute gives a numeric result. The optional parameters are assigned some default values. These values are returned in case there is no caller information. Inside the constructor and AddMethod() the code simply outputs the parameter values to the Output window using Debug.WriteLine() statements.

The Employee class thus created is used by the Windows Forms application as follows:

private void button1_Click(object sender, EventArgs e)
{
    Employee emp = new Employee();
    emp.EmployeeID = int.Parse(textBox1.Text);
    emp.FirstName = textBox2.Text;
    emp.LastName = textBox3.Text;
    MessageBox.Show(emp.AddEmployee());
}

The Click event handler of the Add Employee button simply creates a new instance of the Employee class, assigns property values and calls the AddEmployee() method.

If you run the Windows Forms application and see the Output window you should see this:

The Output window shows the caller information

The Output window shows the caller information

As you can see the Output window shows the caller information as expected.

Using [CallerMemberName] with INotifyPropertyChanged Interface

Though the primary use of caller info attributes is in debugging and tracing scenarios, you can use the [CallerMemberName] attribute to avoid using hard-coding member names. One such scenario is when your class implements the INotifyPropertyChanged interface. This interface is typically implemented by data bound controls and components and is used to notify the user interface that a property value has changed. This way the UI can refresh itself or do some processing. To understand the problem posed by hard-coding property names see the modified Employee class below:

public class Employee:INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private int intEmployeeID;
    public int EmployeeID
    {
        get
        {
            return intEmployeeID;
        }
        set
        {
            intEmployeeID = value;
            if (PropertyChanged != null)
            {
               PropertyChangedEventArgs evt = new PropertyChangedEventArgs("EmployeeID");
               this.PropertyChanged(this, evt);
            }
        }
    }

    private string strFirstName;
    public string FirstName
    {
        get
        {
            return strFirstName;
        }
        set
        {
            strFirstName = value;
            if (PropertyChanged != null)
            {
               PropertyChangedEventArgs evt = new PropertyChangedEventArgs("FirstName");
               this.PropertyChanged(this, evt);
            }
        }
    }

    private string strLastName;
    public string LastName
    {
        get
        {
            return strLastName;
        }
        set
        {
            strLastName = value;
	    if (PropertyChanged != null)
            {
               PropertyChangedEventArgs evt = new PropertyChangedEventArgs("LastName");
               this.PropertyChanged(this, evt);
            }
        }
    }

    public string AddEmployee([CallerMemberName]string sourceMemberName="",
                              [CallerFilePath]string sourceFilePath="",
                              [CallerLineNumber]int sourceLineNo=0)
    {
       ...
    }
}

The Employee class now implements INotifyPropertyChanged interface. Whenever a property value is assigned it raises PropertyChanged event. The caller (Windows Forms in this case) can handle the PropertyChanged event and be notified whenever a property changes. Now the problem is that inside the property set routines the property names are hard-coded. If you ever change the property names you need to ensure that all the hard-coded property names are also changed accordingly. This can be cumbersome for complex class libraries. Using the [CallerMemberName] attribute you can avoid this hard-coding. Let’s see how.

To use the [CallerMemberName] attribute to avoid hard-coding the property names you need to do a bit more work. You need to create a generic helper method that internally assigns the property values. The following code shows how this can be done:

protected bool SetPropertyValue<T>(ref T varName, T propValue, [CallerMemberName] string propName = null)
{
    varName = propValue;
    if (PropertyChanged != null)
    {
        PropertyChangedEventArgs evt = new PropertyChangedEventArgs(propName);
        this.PropertyChanged(this, evt);
        Debug.WriteLine("Member Name : " + propName);
    }
    return true;
}

The SetPropertyValue() method uses only the [CallerMemberName] attribute. It takes three parameters. The first reference parameter is the variable that holds a property value (strFirstName for example). The second parameter is the new property value being assigned to the property. Finally, the third optional parameter supplies the caller member name. Inside the SetPropertyValue() method you assign the property value to the variable, raises the PropertyChanged event and calls Debug.WriteLine() as before.

Now, you need to call the SetPropertyValue() method inside the property set routines as shown below:

private string strFirstName;
public string FirstName
{
    get
    {
        return strFirstName;
    }
    set
    {
        SetPropertyValue<string>(ref strFirstName, value);
    }
}

Now when you assign any property value, the set routine will call the SetPropertyValue() method and pass its name to the SetPropertyValue() method. Inside the SetPropertyValue() method you use this name (propName parameter) without hard-coding the actual property name. 

Summary

.NET Framework 4.5 introduces Caller Info Attributes that can be used to obtain information about the caller of a method. Three attributes, viz. [CallerMemberName], [CallerFilePath] and [CallerLineNumber] supply caller name, its source file and the line number at which the call was made. You can use caller info attributes for tracing, debugging, logging or diagnostic purposes.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read