C# Language Attributes Caller info attributes

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Caller info attributes can be used to pass down information about the invoker to the invoked method. The declaration looks like this:

using System.Runtime.CompilerServices;

public void LogException(Exception ex,
                         [CallerMemberName]string callerMemberName = "",
                         [CallerLineNumber]int callerLineNumber = 0,
                         [CallerFilePath]string callerFilePath = "")
{
    //perform logging
}

And the invocation looks like this:

public void Save(DBContext context)
{
    try
    {
        context.SaveChanges();
    }
    catch (Exception ex)
    {
        LogException(ex);
    }
}

Notice that only the first parameter is passed explicitly to the LogException method whereas the rest of them will be provided at compile time with the relevant values.

The callerMemberName parameter will receive the value "Save" - the name of the calling method.

The callerLineNumber parameter will receive the number of whichever line the LogException method call is written on.

And the 'callerFilePath' parameter will receive the full path of the file Save method is declared in.



Got any C# Language Question?