Friday, April 12, 2013

Finally understand the purpose of event accessors in .NET

As most people who deal with .NET are aware, C# (and also VB.NET) have Properties and Events.  In the case of properties, there are property accessors (get and set) which you can leave to the compiler to define, or you can define your own custom accessors. Similarly, there are event accessors (e.g. add and remove) so that you can customize subscriptions to your event handlers. Until today, I never understood why, until I read the MSDN article on Advanced C#. The reason is explained near the end of the section called "Standard Event Pattern", and it's pretty simple and common sense: in classes where you have a significant number of events (e.g. WPF / Forms Controls) and only a few of them are likely to be subscribed to, you can achieve a smaller memory footprint by overriding the event accessors and placing the event subscribers in an internal IDictionary, rather than using compiler-generated event accessors. In the former case, you'll have to store only the subscribers + the dictionary, whereas in the latter case, you'll have to store the subscribers + n events, and the latter is likely to be far larger than the former.

No comments: