Event Accessors, You can encapsulate events too ;)
This is another "How I missed this" kind of things,
All of us know Accessors like properties & indexers, and almost everybody says that it applies for all data types, but almost nobody knows that events have its own accessors that you can use to encapsulate class events as same as you do with private class members.
However, the syntax is not the same, you don't write set, get blocks, but you use add, remove.
consider this example
public class MyClass
{
private event EventHandler _somethingHappened;
public event EventHandler SomethingHappened
{
add
{ _somethingHappened += value; }
remove
{ _somethingHappened -= value; }
}
}
as you can see, we have a private event of type EventHandler then we added an accessor for it called SomethingHappened which refers to the private _somethingHappened.
and the surprise that this is available since version 1.0 of .net !!!
I think if you tried this in VS 2003 you will not get syntax highlighting for add, remove keywords but the compiler will not complain, but in VS 2005 the syntax highlighting will work.
Have fun