Why can't I access members of an event that is a member of a different type?

Note: was it inspired by WebBrowser Event Properties?

Why can I access MulticastDelegateevent members in a type that declares an event, but not outside it?

For example:

using System;

class Bar
{
    public static event Action evt;
}

class Program
{
    static event Action foo;
    static Bar bar;

    static void Main()
    {
        // this works
        Delegate[] first = foo.GetInvocationList();

        // This does not compile and generates the following
        // error:
        //
        // The event 'Bar.evt' can only appear on the 
        // left hand side of += or -= (except when used 
        // from within the type 'Bar')
        Delegate[] second = bar.evt.GetInvocationList();
    }
}

It seems to me that this is something very simple that I do not see.

+3
source share
1 answer

The event does not display the field and its value - it simply provides a subscription method and a unsubscribe method, similar to how properties simply expose a getter and setter.

From the outside of the class, everything you can do with the event, subscribe to it or refuse it. This is his goal - for encapsulation.

. .

+5

Source: https://habr.com/ru/post/1708101/


All Articles