Delegates - help

  • Thread starter Thread starter Timothy
  • Start date Start date
T

Timothy

Hi,
I'm trying to understand how delegates work in C#. Lets say we have:
public delegate int MyDelegate(int a, int b);
public event MyDelegate MyEvent;
public int MyFunc(int a, int b) { return a+b; }

In order to assign the delegate to MyEvent (omitting some detail):
MyEvent += new MyDelegate(MyFunc);

In order to un-assign the delegate to MyEvent:
MyEvent -= new MyDelegate(MyFunc);

Now, my question is, why not use = instead of += and -=?

Eg, assign:
MyEvent = new MyDelegate(MyFunc);
Eg. un-assign:
MyEvent = null;

I hope I have the right idea :-)

Thanks heaps in advance,

Tim.
 
Timothy said:
Now, my question is, why not use = instead of += and -=?

Eg, assign:
MyEvent = new MyDelegate(MyFunc);
Eg. un-assign:
MyEvent = null;

Because an event can hold multiple subscribers. In other words, if there
were 5 objects interested in your event, each of them could attach (using
+=) to the event, so when the event fires, they all get notified. This is
essentially the broadcast observer pattern. There can be many observers to a
particular event.

--
Regards,

Tim Haughton

Agitek
http://agitek.co.uk
http://blogitek.com/timhaughton
 
Timothy said:
Hi,
I'm trying to understand how delegates work in C#. Lets say we have:
public delegate int MyDelegate(int a, int b);
public event MyDelegate MyEvent;
public int MyFunc(int a, int b) { return a+b; }

In order to assign the delegate to MyEvent (omitting some detail):
MyEvent += new MyDelegate(MyFunc);

In order to un-assign the delegate to MyEvent:
MyEvent -= new MyDelegate(MyFunc);

Now, my question is, why not use = instead of += and -=?

Here's a web page that explains delegates:

http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=18

note the types of delegates, Single Cast delegate and Multi Cast delegate.
 
Back
Top