I often want to write something like this:
new Form { Text = "Caption", Controls = { new Button { Text = "Button 1", Click = (s, e) => MessageBox.Show("Button 1 Clicked"), Location = new Point(10, 10) }, new Button { Text = "Button 2", Click = new EventHandler(Button2Clicked), Location = new Point(10, 40) }, new Button { Text = "Button 3", Click = Button3Clicked, Location = new Point(10, 70) }, }, }
The initializer syntax is just sugar, so why can't the compiler determine how to generate code to subscribe to events?
Give me some sugar, baby!
When the initializer syntax was invented, someone had to think about events and reject them. I try to imagine what could be a rationale, and I start empty.
Is it because an event is a multi-sheeted object that can have more than one subscriber? No, this is the initialization process; There can be no other subscribers. [Updated] Not true, initializers are applied after construction, and the object subscribes to its own events .
Note to Eric: I heard why C # does not implement the X-speech function. In this case, someone was already there, implementing initializers.
Update
There seems to be a contradiction / confusion because I used Click = in my example. The actual syntax is not relevant to the question. Click += would also be easy, which reflects how you usually add a handler. I prefer the former because it is consistent with the rest of the initializer syntax, but in the end I donβt care if I can subscribe to an event in the initializer list.
Another update
I understand that adding a function is now probably unlikely. The first question that comes to mind is that Intellisense needs to be updated. There are probably many other things that would make it difficult to add this feature now. My question is: why didnβt they add it in the first place. There must have been something irresistible that triggered a no vote.