Книга: C# 2008 Programmer

Difference between Events and Delegates

Difference between Events and Delegates

Events are implemented using delegates, so what is the difference between an event and a delegate? The difference is that for an event you cannot directly assign a delegate to it using the = operator; you must use the += operator. 

To understand the difference, consider the following class definitions — Class1 and Class2:

namespace DelegatesVsEvents {
 class Program {
  static void Main(string[] args) {}
 }
 class Class1 {
  public delegate void Class1Delegate();
  public Class1Delegate del;
 }
 class Class2 {
  public delegate void Class2Delegate();
  public event Class2Delegate evt;
 }
}

In this code, Class1 exposes a public delegate del, of type Class1Delegate. Class2 is similar to Class1, except that it exposes an event evt, of type Class2Delegate. del and evt each expect a delegate, with the exception that evt is prefixed with the event keyword.

To use Class1, you create an instance of Class1 and then assign a delegate to the del delegate using the "=" operator:

static void Main(string[] args) {
 //---create a delegate---
 Class1.Class1Delegate d1 =
  new Class1.Class1Delegate(DoSomething);
 Class1 c1 = new Class1();
 //---assign a delegate to del of c1---
 c1.del = new Class1.Class1Delegate(d1);
}
static private void DoSomething() {
 //...
}

To use Class2, you create an instance of Class2 and then assign a delegate to the evt event using the += operator:

static void Main(string[] args) {
 //...
 //---create a delegate---
 Class2.Class2Delegate e2 =
  new Class2.Class2Delegate(DoSomething);
 Class2 c2 = new Class2();
 //---assign a delegate to evt of c2---
 c2.evt += new Class2.Class2Delegate(d1);
}

If you try to use the = operator to assign a delegate to the evt event, you will get a compilation error:

c2.evt = new Class2.Class2Delegate(d1); //---error---

This important restriction of event is important because defining a delegate as an event will ensure that if multiple clients are subscribed to an event, another client will not be able to set the delegate to null (or simply set it to another delegate). If the client succeeds in doing so, all the other delegates set by other client will be lost. Hence, a delegate defined as an event can only be set with the += operator.

Оглавление книги


Генерация: 1.042. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз