Translate

Saturday, April 30, 2011

c# delegates tutorial


What is a Delegate?

In the English language one of the meanings of a delegate is "To commit or entrust to another". Thats precisely what a delegate does in C#. When called, it entrusts (delegates) the job to another method (function). If you are coming from the C++ world, you must note that in C++ delegate is implemented as a function pointer, but C# it is implemented as a class.

In the example below I define a delegate. Then I use instances of that delegate to call two different methods.


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

namespace DelegateExample
{
    class Program
    {

        /*DECLARE THE DELEGATE WITH THE SAME SIGNATURE AS THE FUNCTION TO BE CALLED*/
        delegate void myDelegate();
      

        static void Main(string[] args)
        {
            /*INSTANTIATE THE DELEGATE INSTANCE TO THE FUNCTION THAT NEEDS TO BE CALLED*/

            myDelegate myDel1= SayHello;

            myDelegate myDel2 = SayGoodBye;


            myDel1();
            //Displays Hello!


            myDel2();
            //Displays Bye!
        }

        private static void SayHello()
        {
            Console.WriteLine("Hello!");
        }


        private static void SayGoodBye()
        {
            Console.WriteLine("Bye!");
        }

    } 

}


Output window


















One important thing to remember about delegates is that, it can be passed as a parameter (which you cannot do with methods)


Using Delegate as a parameter to a method


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

namespace Delagate
{
    class Program
    {
        delegate int myDelegate(int x, int y);
        static void Main(string[] args)
        {
            int a = 2;
            int b = 3;

            bool doYouWantToAdd = false;
            myDelegate myDel;

            if (doYouWantToAdd == true)
            {
                myDel = Add;
            }
            else
            {
                myDel = Subtract;
            }

            int z = AddOrSubtract(myDel, a, b);
            Console.WriteLine(z);
        }

        static int Add(int a, int b)
        {
            return (a + b);
        }

        static int Subtract(int a, int b)
        {
            return (a - b);
        }

        static int AddOrSubtract(myDelegate myDel, int a, int b)
        {
            //This method accepts a delegate as a parameter
            return myDel(a, b);
        }
    }
}


Using Delegate to create an anonymous method

Anonymous method is a shorthand way to assign a method to a delegate without having to declare a method separately. Anonymous method is an important (but simple) concept to be learned before you can learn Lambda expressions.

In this example below, instead of separately creating an add method, I will directly declare it when I instantiate the delegate.



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

namespace DelegateExample
{
    class Program
    {

        delegate int myDelegate(int a,int b);

        static void Main(string[] args)
        {

            myDelegate myDel1 = new myDelegate(delegate(int a, int b) { return (a + b); });//the add method is an anonymous method here

            int addResult=myDel1(1, 2);
            Console.WriteLine(addResult);//displays 3

        }     

    }

}



2 comments:

  1. So, far...I was searching for this delegate concept..Bunch of tons of thanks to the author...

    ReplyDelete

Comments will appear once they have been approved by the moderator