Caller Info Attributes (C# 5.0)
Starting with C# 5.0, you can tag optional parameters with one of three caller info attributes, which instruct the compiler to feed information obtained from the caller’s source code into the parameter’s default value:
[CallerMemberName]
applies the caller’s member name.[CallerFilePath]
applies the path to the caller’s source code file.[CallerLineNumber]
applies the line number in the caller’s source code file.
The Foo
method in the following
program demonstrates all three:
using System; using System.Runtime.CompilerServices; class Program { static void Main() { Foo(); } static void Foo ([CallerMemberName]
string memberName = null,[CallerFilePath]
string filePath = null,[CallerLineNumber]
int lineNumber = 0) { Console.WriteLine (memberName); Console.WriteLine (filePath); Console.WriteLine (lineNumber); } }
Assuming our program resides in c:\source\test\Program.cs, the output would be:
Main c:\source\test\Program.cs 8
As with standard optional parameters, the substitution is done at
the calling site. Hence, our Main
method is syntactic sugar for this:
static void Main() { Foo ("Main", @"c:\source\test\Program.cs", 8); }
Caller info attributes are useful for writing logging functions, and
for implementing change notification patterns. For instance, a method such as the following can
be called from inside a property’s set
accessor—without having to specify the property’s name:
void RaisePropertyChanged (
[CallerMemberName]
string propertyName = null) { ... ...
Get C# 5.0 Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.