Tuesday, December 18, 2012

Caller Info Attributes in C# 5.0

In c# 5.0 Microsoft has introduced a Caller information attribute. It’s a new feature that is introduced in C# 5.0 and very useful if you want to log your code activities. With the help of this you can implement the log functionality very easily. It can help any programmer in tracing, debugging and diagnostic of any application.
With the help of Caller Information we can get following information over there.

  1. CallerFilePathAttribute: With help of  this attribute we can get full path of source file that contains caller. This will be file path from which contains caller at compile time.
  2. CallerLineNumberAttribute:  With the help of this attribute we can get line number of source file which the method is called.
  3. CallerMemberNameAttribute: With the help of this attribute we can get the method or property name of the caller.

Let’s write a simple example for that to see how its works. Following is a code for that.

using System;
using System.Runtime.CompilerServices;

namespace ParrallelTask
    class Program
        static void Main(string[] args)
            LogInformation("Some information is there too log");

        public static void LogInformation(string message, [CallerMemberName] string memberName = "",
         [CallerFilePath] string filePath = "",
         [CallerLineNumber] int lineNumber = 0)
            Console.WriteLine("Message : {0}", message);
            Console.WriteLine("Member Name : {0}", memberName);
            Console.WriteLine("File path : {0}", filePath);
            Console.WriteLine("Line Number : {0}", lineNumber);

Here you in the above code you can see that I have create a method to log information over there with the All the Caller Information attribute. You can see I have given the attributes with default values as method parameters. Also If you can see I have used System.Runtime.CompilerServices name space as all attributes are there with that name space. Now if you see the LogInformation method carefully then you can see I have printed all the attributes with console.writeline.

Now let’s run the example via pressing F5 and out put is as expected below.

Caller Information attribute in c# 5.0

That’s it. Hope you like it. Stay tuned for more updates..

Shout it

kick it on DotNetKicks.com


Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog


My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews