My colleague and I came across this when looking into getting the invocation list of a delegate. If you create an event in say class X, then you can access the public methods of the event fine from within that class. But (and please ignore stuff like why you'd have public access to class members, this isn't what we're asking!), if we have a class Y instantiating X, and accessing the event within X, it can't call any of the public methods such as GetInvocationList() of the event. We wanted to know how this works. Here is a code sample (read the comments to see what we mean):
public class X
{
public delegate void TestMethod();
public event TestMethod testMethod;
private void rubbish()
{
// can access testMethod.GetInvocationList() fine here
testMethod.GetInvocationList();
}
}
public class Y
{
public Y()
{
X x = new X();
x.testMethod += this.test;
// here it says testMethod can only appear on the left hand side of += or -=
// why is this? (i.e. the below line is invalid)
x.testMethod.GetInvocationList();
}
public void test()
{
}
}
Out of curiosity how do you achieve this, and what's the reason for having this feature avaialble?
Many Thanks Amit
That's what the event
keyword does; it is a modifier that restricts operations other than subscription to the owning class. If you remove the event
keyword you will end up with a plain delegate that clients outside the class can call e.g. the GetInvocationList()
method on.
In a blog post they compare the generated IL code for a plain delegate and an event and it is handled exactly the same. The event
keyword is a compile-time modifier that restricts access to the methods of the delegate. (It also enables use in interfaces). All the details are in the blog post.
I found some info on this - the access to this outside of the declaring class is very restricted - below is from MSDN site (Events tutorial).
Invoking an event can only be done from within the class that declared the event. Hooking up to an event from outside the class that declared it, an event looks like a field, but access to that field is very restricted. The only things that can be done are:
Compose a new delegate onto that field.
Remove a delegate from a (possibly composite) field.
This is done with the += and -= operators. To begin receiving event invocations, client code first creates a delegate of the event type that refers to the method that should be invoked from the event. Then it composes that delegate onto any other delegates that the event might be connected to using +=.
More info is available at the link.
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