C# · Dotnet

Local variables and Anonymous Delegates (TIP)

Dear Reader,

This post is very small and quite known to many folks. But still wanted to share if in case you did not know.

Any ways, I was just playing around with the internals of anonymous delegate as well as reading some articles and books on the same. I really must say its really a nice feature to have it in C# and i believe this is one of those much usable feature we have. I like it you know.

While doing so, i noticed a small thing. Though its not a serious matter to be so worried about, but still as an developer its good to be aware of it.

As you already know how to work with Anonymous delegates, so i shall start off with the point of concern to this post.

This feature makes things much more easier to code and maintain and more flexible to the developer. So i did a small playing code like below:

public static void Main(string[] args)         
      int someVal = 10;             
      Action output = () => { 
        for (int i = 0; i < 10; i++)        

The above code looks very simple you say? Yes it is. But what one needs to notice is in behind the scenes here. The reason is that the local variable someVal of type Integer in Main method is local to this method scope. So if you as a developer write some code assuming that the life time of this local variable is very short and you write some long processing Anonymous delegate in the same method then you should be aware that this local variable scope/lifetime is extended much longer than what you actually preferred it to be provided if your using this variable inside the same delegate.

Anonymous Delegate

This is because the compiler converts the anonymous delegate to a class type by giving its own fancy name internally in the IL. So it pushes this local variable to a class member/field level, thus expanding its life time than what it usually is. So if this anonymous delegate runs longer in time viz. say it is launched inside a thread. then this local variable life time is much extended even though your actual control is out of this method already. So be careful your maintaining pretty big data structure as local variable and also have a lenghty time consuming delegate written in the same local scope.

So just be aware what is going on behind the scenes, that shall make you not having sudden surprises in your code 🙂


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s