Wednesday 19 March 2014

Sample code which uses Delegates and Without using Delegates

You can think of a delegate type as being a bit like an interface with a single method. It specifies the 
signature of a method, and when you have a delegate instance, you can make a call to it as if it were a
method with the same signature. Delegates provide other features, but the ability to make calls with a
particular signature is the reason for the existence of the delegate concept.

we will see the implementation of calculating two numbers (Addition and Multiplication) using delegates and with out using delegates.


without using Delegate:


without using delegates, we need to create interface and implement that interface in two classes. after that we have to create objects for them and access them using object.methodname.


here is the code for it:

-------------------------------------------------------
namespace WithAndWithoutDelagates
{
    interface calculate1
    {
        int Eval(int a, int b);
       
    }
    class Add:calculate1
    {
        int calculate1.Eval(int a, int b)
        {
            return a + b;
        }
    }

    class Multiply : calculate1

    {
        int calculate1.Eval(int a, int b)
        {
            return a * b;
        }
    }
}

//////////////////////////////////////////////////////////////////////////////

 class Program
    {
static void Main(string[] args)
        {
           Console.WriteLine(DoWork1(new Multiply()));

            Console.WriteLine(DoWork1(new Add()));

            Console.ReadLine();
        }

        static int DoWork1(calculate1 f)

        {
            return f.Eval(20, 30);
         
        }
}

///////////////////////////////////////////////////////////////////////////

using delegates:

No interfaces, no clunky .eval stuff, no object instantiation, just simple function-pointer like usage, for a simple task.

-------------------------------------------------
 class Program
    {
        public delegate int calculate(int x, int y);

        static void Main(string[] args)

        {
            calculate del1 = new calculate(Add);
            calculate del2 = new calculate(Multiply);

   Console.WriteLine(DoWork(del1));

            Console.WriteLine(DoWork(del2));
            Console.ReadLine();
        }

        static int Add(int x, int y) 

        {
            return x+y;
        }

        static int Multiply(int x, int y)

        {
            return x*y;
        }

        static int DoWork(calculate f)

        {           
            var res = f(20, 30);
            return res;
        }

    }

No comments:

Post a Comment