If I write something like the code below,
class MainClass
{
static EventHandler _myEvent= delegate{};
static event EventHandler MyEvent
{
add{_myEvent += value;}
remove{_myEvent -= value;}
}
public static void Main (string[] args)
{
MyEvent(null,EventArgs.Empty);
}
}
the compiler will complain: Error CS0079: The event MainClass.MyEvent' can only appear on the left hand side of
+=' or `-=' operator .
Why does something as weird as this exist at all? If I can't fire an event directly, why would I use such a thing in the first place? Is that a bug(I'm using mono) or deliberate delicate design? Could anyone please teach me the rationale behind this? Thanks in advance.
You can only access an event in the declaring class. Behind the scenes, .NET creates private instance variables to hold the delegate.
The compiler is actually creating a public event, and a private field. You can access the field directly from the same class or nested classes. From external classes, you would only be allowed to subscribe/unsubscribe.
Great information from Jon Skeet is available here on as to why this is and how it works.
You need to invoke your manually declared backing delegate to raise the event: replace MyEvent(null, EventArgs.Empty)
with _myEvent(null, EventArgs.Empty)
. If you think about it, the custom add/remove could be storing the delegates anywhere, which is why you can't retrieve and invoke them the way you've written it...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With