Subscribing to event while creating object in C#
c#, events
Solution
No, unfortunately event subscription isn't supported within object initializers. It would make it really simple to create GUIs in some cases, but no...
The half-way house is:
Checkbox c = new CheckBox { Name = "TheCheckBox" };
c.Checked += c_Checked;
(Ideally renaming `c_Checked` to a name which is actually meaningful - I hate the VS-generated names here...)
Problem
In C# (.NET 4.5) I would like to subscribe to an event while I'm creating an object. The following, of course, would work: ``` CheckBox c = new CheckBox(); c.Name = "TheCheckBox"; c.Checked += c_Checked; ``` But want to find out if it's possible to do something along the lines of: ``` CheckBox c = new CheckBox() { Name = "TheCheckBox", Checked += c_Checked } ``` Post-discussion edit: This is in order to accomplish is something like: ``` MyUniformGrid.Add(new CheckBox() { Name = "TheCheckBox", Checked += CheckHandler }); ```