0

Possible Duplicate:
The purpose of delegates

What is actual use of Delegate in .Net

Community
  • 1
  • 1
Aman
  • 33
  • 1
  • 5
  • Aman, I suggest you to go through some of the online material on .net delegates. This is a very basic topic for which there are enough answers even in Stack overflow http://msdn.microsoft.com/en-us/magazine/cc301810.aspx (-1 for the question) – Sandeep G B Apr 19 '11 at 04:53
  • you could have so easily "googled" this ! – painotpi Apr 19 '11 at 04:53

1 Answers1

0

A delegate in C# allows you to call a group of methods that are specified at runtime instead of one method that is specified at compile-time. Events in the system are handled using delegates because that allows them to raise one event and call a whole slew of methods specified by the different listeners that have subscribed to the event.

public class EventRaiser
{
    public delegate void SomethingHappened();

    public SomethingHappend OnSomethingHappened
    { get; set; }
}

public class Listener
{
    public void DoSomething()
    {
        //Do something
    }
}

public class OtherListener
{
    public void DoSomethingDifferent()
    {
        //Do something different
    }
}

EventRaiser raiser = new EventRaiser();
Listener listener = new Listener();
OtherListener other = new OtherListener();

raiser.OnSomethingHappened += listener.DoSomething;
raiser.OnSomethingHappened += other.DoSomethingDifferent;

//This call will call both DoSomething and DoSomethingDifferent
raiser.OnSomethingHappened();
Kyle Sletten
  • 5,365
  • 2
  • 26
  • 39