Here’s an interesting question I never really thought about until I had a conversation with a co-worker last week.
When we add an event handler, we use syntax such as:
Button1.Click += ClickHandler
As far as I can tell, we use += synonymously with “add” and -= synonymously with “remove”.
So my question is, why did the language creators choose to use this sort of syntax? Why not Button1.Click.Add(ClickHandler)?
If it just means add, why wouldn’t the framework creators overload the += operator for List instead of .Add()?
I imagine it’s the same reason which explains the existence of AddHandler and RemoveHandler in VB.Net but I have no idea what that reason is.
Why is there special language syntax for adding and removing event handlers?
Very subjective question, the guys that defined the syntax don’t post to SO so it mind reading is required to guess at their motivations 14 years ago. Having a stab at it anyway:
An event is the exact equivalent of a property. Just like a property limits access to a field, an event limits access to a delegate object. A property has a getter and a setter. Only the = symbol is required to invoke them. One is enough, the compiler can figure out if the setter or the getter is intended from location of the property identifier relative to the = symbol (left is setter, right is getter).
An event has three accessors: add, remove and raise. Raise is not implemented in C# (unlike other languages) so we just need syntax for add and remove. We can’t do with just one symbol like we can with properties, placement isn’t helpful. The most natural symbol for add is
+, for remove is-. It also behaves somewhat as an assignment since it logically (and in practice) re-assigns the underlying delegate object. So natural choices are+=and-=.No idea if the designers in fact followed the same logic. The VB.NET designers certainly didn’t, they picked language keywords to map to accessors (AddHandler, RemoveHandler, RaiseEvent). But C# is the kind of language where syntax brevity and an absolute minimum number of keywords were strong design goals. C++/CLI is pretty similar to C# but with support for the raise accessor and no syntax sugar at all to create a delegate object. Which gives it capabilities beyond C#, it isn’t limited to making this the delegate target, a feature called “unbound delegates”.
One final note, that delegate object creation syntax sugar that C# has but C++/CLI doesn’t is pretty important. Because if you write it out, you’ll get code like this:
Which bedevils the mind of any programmer starting with .NET programming. You have to create a new delegate object in order to unsubscribe an event??? Yes you do. The sugar is a lot more understandable:
The compiler generates the same code anyway. Also the probable reason that VB.NET went with keywords.