C #: Get information about the caller of a method

C#

C#
Obtaining information about the caller of a method is very useful in the property binding and log function scenarios. Traditionally, the following processes would be implemented:

to identify the calling method:

To simply identify the calling method, one can still examine the stack trace, in which the StackFrame objects (namespace System.Diagnostics) provide the GetMethod and GetFileName methods.

to pass the name of a property:

For example, in the case of the binding, we use the nameof() statement which keeps the compilation link between the name of the property and its value. In any case we do not use strings because if we rename the property then the binding is broken because the chain is out of date.

example :

string _MyProp;
public string MyProp {
    set {
        _MyProp = value;
        NotifyPropertyChanged(nameof(MyProp));
    }
}

Starting from C# 4.5, we can do much better with the method parameter attributes provided by the System.Runtime.CompilerSerices namespace :

  • CallerFilePathAttribute : caller’s file path
  • CallerLineNumberAttribute : caller line number
  • CallerMemberNameAttribute : caller member name (method name or property name)

The NotifiyPropertyChanged method can then be called without necessarily providing the parameter name:

string _MyProp;
public string MyProp {
    set {
        _MyProp = value;
        NotifyPropertyChanged();    /* no more parameter! */
    }
}

protected void NotifyPropertyChanged( [CallerMemberName] string propName = "")    /* propName is initialized with CallerMemberName if it is not defined */
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}

Log function:

A log function will be able to receive valuable information about the caller in the same way:

public void Log(
    string text,
    [System.Runtime.CompilerServices.CallerMemberNameAttribute] string member = "",
    [System.Runtime.CompilerServices.CallerFilePathAttribute] string filePath = "",
    [System.Runtime.CompilerServices.CallerLineNumberAttribute] int lineNumber = 0) 
{
    System.Diagnostics.WriteLine($"{text} | {member} | {filePath}:{lineNumber}");
}

The C# log library NAccLogger use this principles to provide a high level of details in log traces. You can read more about it in this article.

Leave a Reply