Welcome to SpellCoder Sign in | Join | Help

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
kick it on DotNetKicks.com
Published Tuesday, November 21, 2006 4:58 PM by Mohammed Hossam
Filed Under: ,

Comments

# re: Event Accessors, You can encapsulate events too ;)

Tuesday, November 21, 2006 9:56 AM by Adel
Seems like the original implementation of the well know EventHandler.

# re: Event Accessors, You can encapsulate events too ;)

Tuesday, November 21, 2006 1:33 PM by zahmed
nice

# re: Event Accessors, You can encapsulate events too ;)

Wednesday, November 22, 2006 1:55 PM by Michal Talaga
I have posted an article on the same topic a while back, which you can access here:
http://vaultofthoughts.net/EventPropertiesMemoryEfficientEvents.aspx

It focused on how you can use the feature to create a momry efficien events.
Be sure to also check my other article regarding the need to unhook event handlers:
http://vaultofthoughts.net/RememberToUnhookTheEventHandlers.aspx

# re: Event Accessors, You can encapsulate events too ;)

Wednesday, November 22, 2006 4:31 PM by Adel
really nice, didn't think of that before
good one for "How I missed this", thanks
Anonymous comments are disabled