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:
CallerMemberName
for receiving the name of the method that called this oneCallerFilePath
for the name of the full path of the source file that called this methodCallerLineNumber
for 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:
.ctor
for constructors.cctor
for static constructorsFinalize
for destructorsop_operationName
for operator overloadsop_Implicit
for implicit conversion operatorsop_Explicit
for explicit conversion operators