C# Caller Info Attributes

C# provides caller info attributes to get information about the caller method. By using Caller Info attributes, we can get following information.

  • Location of source file
  • Line number at which method is called
  • Caller method name

This information is helpful for tracing and debugging of the source code.

To implement this feature, we need to use System.Runtime.CompilerService namespace in our application. This namespace contains the following caller info attributes.

TypeAttributeDescription
StringCallerFilePathAttributeIt is used to get full path of the source file that contains the caller.
IntegerCallerLineNumberAttributeIt is used to get line number in the source file at which the method is called.
StringCallerMemberNameAttributeIt is used to get caller method name.

A method which we want to call must use optional parameters. These optional parameters are set to default value. C# compiler set caller info to these parameters during execution of the method.

Let's see an example.

C# Caller Method Info Example

Output

Caller method Name: Main
Caller method File location: f:\C#\C# Features\CSharpFeatures\CallerInfoExample.cs
Caller method Line number: 10





Latest Courses