You can tag optional parameters with one of three caller info attributes.
Caller Info Attributes instruct the compiler to feed information obtained from the caller's source code into the parameter's default value.
Attribute | Meaning |
---|---|
[CallerMemberName] | the caller's member name |
[CallerFilePath] | the path to caller's source code file |
[CallerLineNumber] | the line number in caller's source code file |
The Test method in the following program demonstrates all three:
using System; using System.Runtime.CompilerServices; class Program { static void Main() => Test(); static void Test ( [CallerMemberName] string memberName = null, [CallerFilePath] string filePath = null, [CallerLineNumber] int lineNumber = 0) { Console.WriteLine (memberName); Console.WriteLine (filePath); Console.WriteLine (lineNumber); } }
The substitution is done at the calling site.
The code above is converted to as follows:
static void Main() => Test ("Main", @"c:\source\test\Program.cs", 6);