Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribing to event while creating object in C#

Tags:

c#

events

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
});
like image 220
mbaytas Avatar asked Jul 30 '13 08:07

mbaytas


People also ask

How do I subscribe to an event in another class?

You just subscribe to the event on the other class the same way you would to an event in your form. The three important things to remember: You need to make sure your method (event handler) has the appropriate declaration to match up with the delegate type of the event on the other class.

How do I subscribe to events in a channel?

To subscribe to events, call the EvtSubscribe function. You can subscribe to events from one or more Admin or Operational channels. The channel can exist on the local computer or a remote computer. To specify the events that you want to subscribe to, you can use an XPath query or a structure XML query.

How do I subscribe to events in Salesforce?

Subscribing to Events. To subscribe to events, call the EvtSubscribe function. You can subscribe to events from one or more Admin or Operational channels. The channel can exist on the local computer or a remote computer.

How do I subscribe to events using an anonymous method?

To subscribe to events by using an anonymous method. If you will not have to unsubscribe to an event later, you can use the addition assignment operator (+=) to attach an anonymous method to the event.


1 Answers

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...)

like image 83
Jon Skeet Avatar answered Oct 21 '22 08:10

Jon Skeet