-1

Can anybody explain to me why we need delegates and what are the advantages of them?

Here is a simple program I have created with and without delegates (using plain methods):

Program with without delegates:

namespace Delegates
{
    class Program
    {
        static void Main(string[] args)
        {
            abc obj = new abc();

            int a = obj.ss1(1, 2);
            int b = obj.ss(3,4);

            Console.WriteLine("the result of ss is {0} and the result of ss1 is {1}", a, b);

            Console.ReadKey();
        }
    }

    class abc
    {
        public int ss(int i, int j)
        {
            return i * j;
        }

        public int ss1(int x, int y)
        {
            return x + y;
        }
    }
}

Program with Delegates:

namespace Delegates
{
    public delegate int my_delegate(int a, int b);

    class Program
    {    
        static void Main(string[] args)
        {
            my_delegate del = new my_delegate(abc.ss);    
            abc obj = new abc();

            my_delegate del1 = new my_delegate(obj.ss1);

            int a = del(4, 2);    
            int b = del1(4, 2);

            Console.WriteLine("the result of ss is {0} and the result of ss1 is {1}", a, b);
            Console.ReadKey();    
        }    
    }

    class abc
    {    
        public int ss(int i, int j)
        {    
            return i * j;    
        }

        public int ss1(int x, int y)
        {    
            return x + y;    
        }    
    }    
}

Both programs give the same results, so what is advantage of using Delegates?

Thanks.

Prabu
  • 4,097
  • 5
  • 45
  • 66
King_Fisher
  • 1,171
  • 8
  • 21
  • 51
  • it is not supposed to similar question, I have tried to understand the delegates ,but i'm not able to understand why we need ,that why i've created a thread here. – King_Fisher Aug 17 '15 at 13:29
  • @King_Fisher The linked answers provide a lot of examples what you can do with delegates. Have you read them? – Sebastian Negraszus Aug 17 '15 at 13:40

1 Answers1

2

Delegate is designed to program in event-driven approach which creates a more decoupled source code.

With delegates, we can create something like publisher-subscriber pattern where subscribers can register to receive events from publishers.

We usually see delegates in use as event handlers. For example, with delegates we can create reusable controls by dispatching an event when something happens (e.x: click event,...), in this case, the control is the publisher, any code (subscriber) interested in handling this event will register a handler with the control.

That's one of the main benefits of delegates.

There are more usages pointed out by @LzyPanda in this post: When would you use delegates in C#?

Community
  • 1
  • 1
Khanh TO
  • 48,509
  • 13
  • 99
  • 115