Possible Duplicate:
The purpose of delegates
What is actual use of Delegate in .Net
Possible Duplicate:
The purpose of delegates
What is actual use of Delegate in .Net
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();