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 which include:
CallerMemberNamefor receiving the name of the method that called this oneCallerFilePathfor the name of the full path of the source file that called this methodCallerLineNumberfor the line number within that source file
Code
C#
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);
}C#
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
Non-method names will appear as the C# compiler-generated internal names, that is:
.ctorfor constructors.cctorfor static constructorsFinalizefor destructorsop_operationNamefor operator overloadsop_Implicitfor implicit conversion operatorsop_Explicitfor explicit conversion operators