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?
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?
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.
Also you might want to take a look at this post about avoiding checking for null delegates
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.
+= 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.
Check out Chris Sells .NET Delegates: A C# Bedtime Story for a great guide to delegates and events. Informative and quite entertaining.