Method Caller Information in C Sharp 5.0

Before we understand Method Caller Information feature of C# 5.0, we need to understand Optional Parameter feature of C# 4.0.

C Sharp 4.0 introduced Optional Parameter feature . According to this feature, in function call only required parameters are needed to be passed. If value of Optional Parameters are not provided then they will take default constant value. To understand it better, let us take following function as example.


static void Display(string Name, int age,string Nationality="Indian")
{

Console.WriteLine("Hey " + Name + " you are " + age + " old " + Nationality);
}

In function Display, Nationality is an optional parameter. So while calling this function you will get intellisense suggesting you that if not provided parameter Nationality will take constant string value “Indian”

image

You can call Display function omitting value of parameter Nationality as following

static void Main(string[] args)
{
Display("dj", 28);
Console.ReadKey(true);

}

In output you will notice that value of parameter Nationality is set to default string constant “Indian”

image 
Now you can see that Optional Parameters has taken the default constant value. C# 5.0 gives us liberty or allow us to attribute optional parameter with caller info attributes. By providing caller info attributes at the runtime optional parameter value will be replaced by dynamic values for caller info attributes. There are three caller info attributes are available,

image

Let us go ahead and rewrite Display function with Method Caller Information attribute on optional parameters.

image

You see in above function definition [see the rectangle], we have attributed three optional parameters with method caller information. We can display method caller information as following,


static void Display(string Name,
int age,
string Nationality="Indian",
[CallerMemberName] string Caller = "",
[CallerFilePath] string file="",
[CallerLineNumber] int line=0)
{

Console.WriteLine("Hey " + Name + " you are " + age + " old " + Nationality);
Console.WriteLine("This function is called  from member " + Caller + " file " + file + " line " + line);
}

Now when you call the function you will get method caller information printed. Expected output would be as following

image 
Method Caller Information is particularly very useful in logging of the application. For high level logging, I would consider using Method Caller Information attributes along with optional parameters. I hope you find this post on Method Caller Information in C# 5.0 useful. Thanks for reading.

2 responses to “Method Caller Information in C Sharp 5.0”

  1. […] Method Caller Information in C Sharp 5.0 and Evolution of C Sharp Language: Picture Blog (Dhananjay Kumar) […]

Leave a comment

Create a website or blog at WordPress.com