How to use Caller Information in C# 5.0
Understand Caller Information in C# 5.0
In this article we will understand one new concept of C# 5.0
called Caller Information. Before start discussion with caller information we
will try to understand how the new feature will help us in project development.
Caller information gives information about caller of any
function. Previously if any exception occurs in the program, it way bit tough
to write all information about error in log file. The reason is we had to trace
the error location using StackTrace property of Exception object. And in
general the output is very lengthy string. In C# 5.0 the caller info feature
has introduced and using this feature we can easily get information about
caller function.
Caller Info attributes
Caller Info supports three attributes and those are
CallerFilePath
:- Return file path of Caller function. Data type is String
CallerLineNumber:-
Return line number of caller function . Data type is int.
CallerMemberName:-
Name of caller method. Data Type is string.
Example:-
Let’s implement small
example with Caller Info attributes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Asynchronious
{
class Test
{
public void dummy(
String message,
[CallerFilePath] string file = "",
[CallerLineNumber] int line = 0,
[CallerMemberName] string member = ""
)
{
{
Console.WriteLine("File Path:- " + file);
Console.WriteLine("Line Number:- " + line);
Console.WriteLine("Member Name:- " + member);
Console.WriteLine("Message:- " + message);
}
}
class Program
{
public static void Main(String[] args)
{
Test t = new Test();
t.dummy("Dummy Message");
Console.ReadLine();
}
}
}
}
Here is sample output.

Few more information
about Caller Info attributes
Caller Info attributes
are sealed classes and inherited from Attribute class.
To
use caller Info, we have to include using
System.Runtime.CompilerServices; namespace
We have to specify default
value of all attributes.
conclusion:-
In this quick article we have learned what is caller info attribute and how to use it in application. It is the feature of C# 5.0 and .NET framework 4.5 is needed to use it in application.