pavanarya

Let us share the knowledge

Delegates ,Anonymous Functions in c#

with one comment

In my previous post we saw about the creation of Delegates and using them.

So there are different ways of instantiating a delegate. In the initial stages delegates were created using new keyword, later by just assigning the name of the function to the delegate declared. Later by creating an inline functions and now we are making use of lambda expressions.

Now let us see them in detail.

Creating and Instantiating Delegate using new keyword
This procedure was initially used in framework 1.0 although we can make use of it even now(in framework 4.5)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AnonymousLambdaFunc
{
    class Program
    {
        delegate string ReturnValueFromList(List<string> lst);
        static void Main(string[] args)
        {
            ReturnValueFromList delobj = ReturnValueStartsWithK;
            List<string> lst=new List<string>(new string[] { "Pavan", "Kiran Mantri", "Rajesh Boda" });
            string ss = ReturnValueStartsWithK(lst);

            ReturnValueFromList basicway = new ReturnValueFromList(ReturnValueStartsWithK);
           string val1= basicway(lst);

        }
        public static string ReturnValueStartsWithK(List<string> lst)
        {
            string retValue = "";
            foreach (string name in lst)
            {
                if (name.StartsWith("Kiran"))
                {
                    retValue = name;
                    break;
                }
            }
            return retValue;  
        } 
    }    
}

So in this way first of all we are supposed to declare a delegate and then instantiate it using new keyword.
Here i am creating a delegate

delegate string ReturnValueFromList(List<string> lst);

later we are instantiating it using new keyword and passing the method that matches the delegate type and now we can make use of the delegate just like the function.

ReturnValueFromList basicway = new ReturnValueFromList(ReturnValueStartsWithK);

//ReturnValueFromList is delegate and ReturnValueStartsWithK is the method which is having same signature and parameters like the delegate

basicway(listobject);//making use of delegate and this will inturn call the method ReturnValueStartsWithK

Directly instantiating the delegates without new keyword:

Later in framework 2.0 a new method of instantiating delegates was introduced that is without making use of new keyword.

// this line should be relaced with ReturnValueFromList basicway = new ReturnValueFromList(ReturnValueStartsWithK);
ReturnValueFromList basicway = ReturnValueStartsWithK;

So instead of creating an delegate object using new we can directly assign it with the name of the function.

Anonymous Functions:

Anonymous method is a method with no name
Anonymous function is nothing but an inline piece of code that can be used on the fly.
So till now if we want to instantiate a delegate we are supposed to follow these steps

1.Declare delegate
2.We are supposed to create a function with same signature and parameters.
3.Instantiate a delegate using new keyword or directly by assigning the method name.
4.make use of the delegate just like a method.

So with anonymous functions step 2 and step 3 can be combined.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AnonymousLambdaFunc
{
    class Program
    {
        delegate string ReturnValueFromList(List<string> lst);
        static void Main(string[] args)
        {
            ReturnValueFromList delobj = ReturnValueStartsWithK;
            List<string> lst=new List<string>(new string[] { "Pavan", "Kiran Mantri", "Rajesh Boda" });
            //Process of instantiating the delegate with the help of anonymous function
            ReturnValueFromList delObject1 = delegate(List<string> lstObject)
            {
                string retValue = "";
                foreach (string name in lstObject)
                {
                    if (name.StartsWith("Kiran"))
                    {
                        retValue = name;
                        break;
                    }
                }
                return retValue;
            };

            string a1 = delObject1(lst);
        }        
    }    
}

So in the above example if we can see we are declaring the delegate and instantiating it by writing a code at the same time.
Here the anonymous function is created and assigned to the delegate

 ReturnValueFromList delObject1 = delegate(List<string> lstObject)
            {
                string retValue = "";
                foreach (string name in lstObject)
                {
                    if (name.StartsWith("Kiran"))
                    {
                        retValue = name;
                        break;
                    }
                }
                return retValue;
            };

Few points about Anonymous functions:

1.The scope of the variable defined inside the anonymous functions is limited to that anonymous function itself.

2.If a variable is declared outside of the anonymous function then it can be used inside the anonymous function(outer variable) and any change made inside the anonymous function will be reflected even after the execution of the anonymous function.

3.We cannot have goto or break or continue statements inside the anonymous function so that the target is outside the anonymous function

            int i = 10;
            ReturnValueFromList delObject1 = delegate(List<string> lstObject)
            {
                i = i + 5;
                string retValue = "";
                foreach (string name in lstObject)
                {
                    goto pavan;
                    if (name.StartsWith("Kiran"))
                    {
                        retValue = name;
                        break;
                    }
                }
                return retValue;
            };

        pavan:
            int k = 0;

Here if we can see we are having a goto statement inside anonymous function and the label is declared outside of the anonymous function. This will throw a compile time error.

4.We cannot have unsafe code inside anonymous functions.

So an anonymous method can be used to reduce the code to some extent

About these ads

Written by pavanarya

April 7, 2012 at 8:32 pm

Posted in c#

One Response

Subscribe to comments with RSS.

  1. Cheers, I just stopped by to visit your blog and thought I’d say I enjoyed myself.

    how to study

    April 10, 2012 at 2:39 am


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 69 other followers

%d bloggers like this: