By using Caller Info attributes, you can obtain information about the caller to a method. You can obtain file path of the source code, the line number in the source code, and the member name of the caller. This information is helpful for tracing, debugging, and creating diagnostic tools.
To obtain this information, you use attributes that are applied to optional parameters, each of which has a default value. The following table lists the Caller Info attributes that are defined in the
System.Runtime.CompilerServices
namespace:
Attribute |
Description |
Type |
CallerFilePath |
Full path of the source file that contains the caller. This is the file path at compile time. |
String |
CallerLineNumber |
Line number in the source file at which the method is called. |
Integer |
CallerMemberName |
Method or property name of the caller. See the Member Names section later in this topic. |
String |
The following example shows how you might use these attributes to trace a caller.
open System.Diagnostics
open System.Runtime.CompilerServices
open System.Runtime.InteropServices
type Tracer() =
member _.DoTrace(message: string,
[<CallerMemberName; Optional; DefaultParameterValue("")>] memberName: string,
[<CallerFilePath; Optional; DefaultParameterValue("")>] path: string,
[<CallerLineNumber; Optional; DefaultParameterValue(0)>] line: int) =
Trace.WriteLine(sprintf $"Message: {message}")
Trace.WriteLine(sprintf $"Member name: {memberName}")
Trace.WriteLine(sprintf $"Source file path: {path}")
Trace.WriteLine(sprintf $"Source line number: {line}")