Malucs Malucs - 5 months ago 13
Android Question

Best option for event subscription

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");
};

Answer

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");
}