Caller Information in C# 5

Caller Information is a new concept introduced in C# 5. It is aimed at providing useful information about where a function was called. It gives information such as:
  • Full path of the source file that contains the caller. This is the file path at compile time.
  • Line number in the source file at which the method is called.
  • Method or property name of the caller.
We specify the following(as optional parameters) attributes in the function definition respectively:

  • [CallerMemberName]  a String
  • [CallerFilePath]            an Integer
  • [CallerLineNumber]     a String
 We use Trace.WriteLine() to output information in the trace window.

here is a C# example:

public void TraceMessage(string message,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string sourceFilePath = "",
        [CallerLineNumber] int sourceLineNumber = 0)
{
    Trace.WriteLine("message: " + message);
    Trace.WriteLine("member name: " + memberName);
    Trace.WriteLine("source file path: " + sourceFilePath);
    Trace.WriteLine("source line number: " + sourceLineNumber);
 
You can use the CallerMemberName in:
 
* Method, Property or Event: They return name of the method, property, or event   from which the call originated. 
 
* Constructors: They return the String ".ctor" 
 
* Static Constructors: They return the String ".cctor"
 
* Destructor: They return the String "Finalize" 
 
* User Defined Operators or Conversions: They return generated member name 
 
Whenever we call the TraceMessage() method, it outputs the required information as 
stated above.
Note: Use only with optional parameters. Caller Info does not work when you do not 
use optional parameters.
Custom Search