delegates explained to SharePoint 2010 developers

I’ve noticed that many people attending my SharePoint courses don’t always have the knowledge of delegate/ anonymous methods/lambda expressions.

Here is how I explain it in 1 page

//myDelegate is a type pointer on a function that takes
//an int and returns an int

    delegate int  myDelegate (int x);

    class Program
    {  
        static int Test(int x)
        {
           return  x+1;
        }
        static void Main(string[] args)
        {
            myDelegate f = new myDelegate(Test);  \\C#1.0
            f(10);
            myDelegate f1 = Test;   \\C#2.0
            f1(10);
            myDelegate f2 = delegate(int x) { return x + 1; };  \\C#2.0 anonymous method
            f2(10);
            myDelegate f3 = ((int x) => {return x + 1 ;}); \\C#3.0 lambda
            f3(10);
            myDelegate f4 = (( x) => { return x + 1; });
            f4(10);
           
        }
    }

Advertisements

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