Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the events with custom accessors cannot be fired directly as the default ones do?

Tags:

c#

events

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.

like image 721
Need4Steed Avatar asked Aug 20 '11 02:08

Need4Steed


2 Answers

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.

like image 156
Bryan Crosby Avatar answered Nov 14 '22 13:11

Bryan Crosby


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

like image 2
Nick Guerrera Avatar answered Nov 14 '22 13:11

Nick Guerrera