A Look at the Caller Info Attributes in C# 5.0

In C# 4.0 or earlier versions, to get the caller information at the called method the caller had to explicitly pass the information as a parameter or by some other means. In order to do that it had to use the Reflection classes that are available under the namespace System.Reflection.

Now C# 5.0 exposes a feature called Caller Info attributes in order to accomplish the task with ease. This article offers an insight about these attributes.

Caller Info Attributes

CallerInfo attributes are specifically designed to decorate the optional parameters of a method, which can then be used by the .NET runtime to inject the caller information. Below are some of the advantages of caller info attributes when compared to the traditional methods of passing the caller information.

1. The caller doesn't have to do anything explicitly. Say for example I have built a component that is going to be used by a client application, using Caller Info Attributes I don’t have to worry about the caller passing the information explicitly; I will always get it through the caller info attributes.

2. There is no need for explicit usage of System.Reflection classes.

3. These attributes will be very helpful while implementing server side tracing or exception logging.

These attributes are encapsulated under the namespace System.Runtime.CompilerServices.

What are they?

There are 3 caller info attributes that come along with C# 5.0 and they are:

1. CallerFilePath

This attribute will provide the path of the file from where the method call is being made.

2. CallerLineNumber

This attribute will provide the line number from where the call is being made.

3. CallerMemberName

This attribute provides the name of the method that is making the call. It also has some special usages, which I will discuss later in this article.

Using Caller Info Attributes

In this section let us create a small application to demonstrate the usage of these CallerInfo attributes in C# 5.0. Create a console application and add the below mentioned code to Program.cs.

namespace CallerInfoAttributes
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintCallerInformation();
 
            Console.ReadLine();
        }
 
        static void PrintCallerInformation([CallerLineNumber] int lineNumber = 0, [CallerFilePath] string filePath = "", [CallerMemberName] string memberName = "")
        {
            Console.WriteLine("Line number from where the call is made: {0}", lineNumber);
            Console.WriteLine("Filepath of the caller: {0}", filePath);
            Console.WriteLine("Member which is making the call: {0}", memberName);
        }
    }
}

When you execute the console application you will exactly see the Caller Info parameters that are being passed.

CallerMemberName – Specialty

The CallerMemberName attribute can be of some special use. For example if you want to decide the business logic based on the caller at runtime then CallerMemberName would help you. Below is a sample piece of code.

namespace CallerInfoAttributes
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 10;
            int j = 5;
            Add(i, j);
            Sub(i, j);
        }
 
        private static void Sub(int value1, int value2)
        {
            Compute(value1, value2);
        }
 
        private static void Add(int value1, int value2)
        {
            Compute(value1, value2);
        }
 
        private static void Compute(int value1, int value2, [CallerMemberName] string memberName = "")
        {
            if (memberName.Equals("Add"))
                Console.WriteLine("Sum = {0}", value1 + value2);
            else
                Console.WriteLine("Difference = {0}", value1 - value2);
        }
    }
}

Also if you are implementing the INotifyProperyChanged interface in your class, you would have been passing the member name as a hard coded string from the property setter while raising the PropertyChanged event. This can be avoided by using the CallerMemberName attribute.

The CallerMemberName would inject specific values based on the caller. Below is the list.

1. If caller is a Method, Property or an event then the name of the caller will be injected.

2. If the caller is a constructor or a static constructor then the value will be injected as .ctor or .cctor respectively.

This is all I had to share about the Caller Info attributes of C# 5.0. Happy reading!



Related Articles

Comments

  • Clean and Simple Article

    Posted by Senthil on 11/19/2013 08:43am

    Really nice article..Thanks Mr.Arun.

    Reply
  • Replica Oakley Eyepatch 2 no tax worldwide

    Posted by pxpxtxtaa on 06/29/2013 08:09am

    Replica Oakley Sunglasses Sale ,Oakley sunglasses lens sunglasses sale silver announcement can be a milestone within the glasses. This new model of sunglasses will provide you with an unprecedented enjoyment and fitness. Dark Oakley sunglasses in the movie "Matrix", has grown to be an important product for all gamers. But the heat with the colloid lately sunglasses Oakley sunglasses sales leadership style. Oakley Outlet ,Oakley been on the last a long time, the will of the individual. Nearly all project, designed, and also the cultivation of personal feeling behind, and carry on being among the best sunglasses within a set of the planet earth. Everybody really wants to wear designer clothing and accessories, can supply detection in the appeal, because everyone really worship the midst of attention. fake Oakley flak Jacket ,The many defending the clothing colors will have to protect yourself, and sometimes terrible events, as the situation is like direct sunlight: unique. The structural characteristics of true contact hobbies polarization and smear easily the portable titanium insole, and O Racks. Your package about shade-hole fashion shades usually care plus the emergence of entirely very impressive around the true Oakley fashion. To find out how the maintenance of good sunglasses can not only extend the duration useful of sunglasses, but additionally can better make sure that the sunglasses eye protection role. Oakley sunglasses are the types who want to protect your professional riders from the sun in the ultimate visual clarity, especially for Kun pounds copy glare, polarized contact lenses into the glasses Oakley Jacket XLJ Polarized, Oakley anti-aircraft guns by strengthening the style, it's totally satisfied to visit your face. Moreover, you provide your electric solar sunroof. Long-term experience in the UV may bring about cataracts, be aware of cover the point of view, while using short of long-term harm to eyes like snow blindness contact lenses cloudy, if your depth of ultraviolet is very high. Popular aspects of many, the trend through history, will appear back, so while using the retro. The superior professional players noted, oakley sunglasses new design and materials will raise the grip force actually sweating. An illustration can be interpreted because classic form of romantic named Oakley Romeo and Juliet "sunglasses. I figured, wallets and handbags are the most well-known ladies, these days I think I need to change my mind soon begin to see the different parts of the title is really crazy sunglasses retailer of ladies.

    Reply
  • Frohman takes Morris by the throat discharge Beijing thin arm most the foreign aids that respect property is not him to not be belonged to0

    Posted by qfundgyxsx on 05/17/2013 06:14pm

    Frohman takes Morris by the throat discharge Beijing thin arm most the foreign aids that respect property is not him to not be belonged to Sport weeklyMa Hong of reporter of engage by special arrangement watchs Beijing to report Frohman's action, pass a data to be able to see: The 2nd, shandong male basket defends with Tao Hanlin and Wu Ke take turns Morris, as a result only part takes Rangmolisi; Whole the second half is Frohman follows Morris contrapuntal, morris is taken only. Frohman takes Morris by the throat, was equal to discharge to drop an arm of Beijing male basket. In cloth of an arm horse, also be twisted terribly by Frohman. From Shandong male basket defend in light of strategy, sui Ran advocate prevent Mabuli, once Mabuli receives a ball in exterior line, frohman and A Ba Si form a triangle with Sui Ran, had done at any time fill the preparation that prevent. The show that does not watch Frohman to be carried in aggression not very grab an eye, but his importance in Shandong team, a bit no less than outstanding special. If say outstanding the word that is aggression axes especially, frohman defends namely the mental cacique of end, he has sacrifice oneself to block the lofty quality of embrasure up, not only can finish man-to-man defend, still can be teammate assist prevent. Shandong male basket 2 go up defend dagger Sui Ran, frohman praise for the most tenacious, most the foreign aids that respects property, with the set match of Dongguan, frohman leads a fight, than home the player can go all out, I should to his uncover, he is the man that I respect most! This match, frohman is punished to leave again, he is this CBA sports season fouls most player, also can saying is to defend the foreign aids [url=http://jordankicks.page4.me/]jordan sneakers for sale[/url] with the most decorous manner. Gong Xiaobin expresses clearly, if do not have Frohman, of Shandong male basket defend resemble impossibly so solid now, go impossibly also so far. Related news

    Reply
  • .Get Grid

    Posted by jagvir on 10/26/2012 05:07am

    Data binding is used by almost all modern applications. It provides simple means to separate the data layer from the presentation layer. Generally, binding means connecting a graphical control property with a data object property. For example, if we have Product class, Label control can be bound to Name property of this control .net grid tutorial is very helpful dapfor. com

    Reply
  • Sir

    Posted by Rich on 10/22/2012 04:07am

    I agree the Add/Sub example is silly, but I think it was only meant for exposition. However, this facility could be great for INotifyPropertyChanged event handling. At the moment you have to require the function be called with a text string holding the name of the property being changed, and the opportunities for these to get out of sync and cause weird behaviour in your programs is huge.

    Reply
  • No changing behavior based on caller

    Posted by Foozinator on 10/18/2012 08:43am

    I can think of a few good uses for caller info (error logging is one), but having a method change behavior based on the caller method name sounds terribly dangerous to me. Debugging a problem could become significantly harder unless that behavior is well documented and easy to find.

    Reply
  • Ye gods, no! Please, no!

    Posted by Ross Patterson on 10/18/2012 05:05am

    "For example if you want to decide the business logic based on the caller at runtime then CallerMemberName would help you." Anyone who writes code that behaves differently depending on where it was called from should be shot, drawn and quartered, and given 50 lashes, not necessarily in that order. In fact, the very fact that caller info attributes enable such bad practice should argue against having them at all.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: August 19, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT You deployed your app with the Bluemix PaaS and it's gaining some serious traction, so it's time to make some tweaks. Did you design your application in a way that it can scale in the cloud? Were you even thinking about the cloud when you built the app? If not, chances are your app is going to break. Check out this upcoming webcast to learn various techniques for designing applications that will scale successfully in Bluemix, for the …

  • A majority of organizations are operating under the assumption that their network has already been compromised, or will be, according to a survey conducted by the SANS Institute. With many high profile breaches in 2013 occurring on endpoints, interest in improving endpoint security is top-of-mind for many information security professionals. The full results of the inaugural SANS Endpoint Security Survey are summarized in this white paper to help information security professionals track trends in endpoint …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds