tags:

views:

142

answers:

5

I have a delegate, say:

public delegate void MyDelegate();

I have an event, say:

public MyDelegate MyEvent;

While invoking the event I am receiving an error message:

"MyEvent += expected ....."

How do I resolve this?

+4  A: 

You can only invoke the event from within the class where you declared it. In any other place, you can only add or remove handlers from the event delegate via the operators += and -=, hence the error message.

Konrad Rudolph
A: 

Also you might want to take a look at this post about avoiding checking for null delegates

bendewey
+1  A: 

If you're trying to use the event from a different class, you need to understand the difference between events and delegates. An event just encapsulates the "subscribe" and "unsubscribe" aspects, not "raise the event". (In fact in IL you can have a member for "raise the event" but C# doesn't support it.)

See my article on events and delegates for more details.

Jon Skeet
I've always wondered by C# didn't support the Raise method since VB and even C++/CLI do and it's actually pretty handy sometimes. Do you know any reason for this decision?
Konrad Rudolph
In my opinion, it breaks encapsulation. A class should be responsible for raising events itself - the event pattern is an observational one. I've never encountered a situation where I wanted to raise an event from "outside" but had a *good* reason to do so (rather than crufty design elsewhere).
Jon Skeet
+4  A: 

+= is associated with events, not just a declaration of a delegate. You are missing the 'event' keyword.

public **event** MyDelegate MyEvent;

Once you have that keyword the += will work for you.

Geoff Cox
A: 

Check out Chris Sells .NET Delegates: A C# Bedtime Story for a great guide to delegates and events. Informative and quite entertaining.

Sean Campbell