When you create a “field-like” event, like this:
public event EventHandler Foo;
the compiler generates a field and an event. Within the source code of the class which declares the event, any time you refer to Foo
the compiler understand that you’re referring to the field. However, the field is private, so any time you refer to Foo
from other classes, it refers to the event (and therefore the add/remove code).
If you declare your own explicit add/remove code, you don’t get an auto-generated field. So, you’ve only got an event, and you can’t raise an event directly in C# – you can only invoke a delegate instance. An event isn’t a delegate instance, it’s just an add/remove pair.
Now, your code contained this:
public EventHandler TypicalEvent;
This is slightly different still – it wasn’t declaring an event at all – it was declaring a public field of the delegate type EventHandler
. Anyone can invoke that, because the value is just a delegate instance. It’s important to understand the difference between a field and an event. You should never write this kind of code, just as I’m sure you don’t normally have public fields of other types such as string
and int
. Unfortunately it’s an easy typo to make, and a relatively hard one to stop. You’d only spot it by noticing that the compiler was allowing you to assign or use the value from another class.
See my article on events and delegates for more information.