views:

95

answers:

1

Note: this was inspired by WebBrowser Event Properties?

Why am I able to access the MulticastDelegate members of an event within the type that declares the event but not outside of it?

For instance:

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();
    }
}

I get the feeling this is something very simple that I am not seeing.

+4  A: 

An event doesn't expose the field and its value - it just exposes a subscription method and an unsubscription method, in a similar way to how properties just expose a getter and a setter.

From outside the class, all you can do with an event is subscribe to it or unsubscribe from it. That's its purpose - for encapsulation.

See my event article for more information.

Jon Skeet
+1 That makes sense - thanks!
Andrew Hare