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
eventkeyword does; it is a modifier that restricts operations other than subscription to the owning class. If you remove theeventkeyword you will end up with a plain delegate that clients outside the class can call e.g. theGetInvocationList()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
eventkeyword 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.