Being able to report where a method is called from is very useful when performing logging or tracing however it is intrusive and error-prone to manually add this information yourself.
C# 5.0 adds attributes in System.Runtime.CompilerServices that you apply to optional parameters. When the caller omits the argument the compiler fills it in:
CallerMemberNamewith the name of the method or property that made the callCallerFilePathwith the full path of the source file containing the callCallerLineNumberwith the line number of the call within that source file
Code
csharp
Customer LoadCustomer(Guid id)
{
Log("Querying for customer " + id);
return db.Customers.FirstOrDefault(c => c.Id == id);
}
void Log(string message, [CallerMemberName] string memberName = "")
{
logger.Log(LogLevel.Info, message, memberName);
}csharp
Customer LoadCustomer(Guid id)
{
Log("Querying for customer " + id, "LoadCustomer");
return db.Customers.FirstOrDefault(c => c.Id == id);
}
void Log(string message, string memberName)
{
logger.Log(LogLevel.Info, message, memberName);
}Notes
- Calls from a property accessor report the property name, which makes
CallerMemberNamea popular way to raiseINotifyPropertyChangedevents without repeating the property name - Other non-method callers appear as their compiler-generated internal names:
.ctorfor constructors.cctorfor static constructorsFinalizefor finalizersop_Additionstyle names for operator overloadsop_Implicitfor implicit conversion operatorsop_Explicitfor explicit conversion operators
- CallerArgumentExpression C# 10.0 adds a similar attribute that captures the source text of an argument