Delegates - help

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.
 
T

Tim Haughton

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
 
K

Kleine Aap

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top