Reputation: 198
Can you tell me which is the best way to create an event or all the options are good?
// OPTION 1
buttonAlert.Click += delegate
{
textChange.Text = string.Format("Hello World");
};
// OPTION 2
buttonAlert.Click +=(sender, e) =>
{
textChange.Text = string.Format("Hello World");
};
// OPTION 3
buttonAlert.Click += delegate (object sender, EventArgs e)
{
textChange.Text = string.Format("Hello World");
};
Upvotes: 4
Views: 207
Reputation: 7850
Its just a matter of preference. In terms of performance are all equivalent.
So, choose based on what you need and prefer.
As a complement of my answer i like to alert that you must unsubscribe a event (-=) after subscrive (+=).
From the documentation:
To prevent your event handler from being invoked when the event is raised, simply unsubscribe from the event. In order to prevent resource leaks, it is important to unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, your subscriber object will not be garbage collected.
Upvotes: 3
Reputation: 6365
I would say that first option is the best when you don´t need the lambda parameters (sender, event). Between second and third I would choose second because it´s cleaner (just a matter of preference.
You can also use a method as a delegate, and it´s probably the best if you want to manage memory correctly. When you use a delegate or lambda there is no way to unsubscribe. That means that even if you destroy or leave the activity/fragment, the object will remain in memory and the garbage collector won´t be able to clear it. In the case the user opens and closes this screen many times, you may get an OutOfMemoryException eventually. This happens very often in Android. This would be the solution:
protected override void OnResume()
{
base.OnResume();
buttonAlert.Click += OnButtonClick;
}
protected override void OnPause()
{
base.OnPause();
buttonAlert.Click -= OnButtonClick;
}
private void OnButtonClick(object sender, EventArgs e)
{
textChange.Text = string.Format("Hello World");
}
Upvotes: 2