DGoodman DGoodman - 2 months ago 10
C# Question

Efficient use of the ICommand interface

I'm beginning a project using Xamarin Forms for cross-platform development of a mobile app. I'm using the MVVM model, of which I have little experience of beyond a few small WPF applications.

I'm using the ICommand interface to create commands and binding to them in the view's XAML, which by default involves a good amount of duplicate code. Xamarin.Forms provides a concrete subtype, Command, of ICommand, which is used as in the discussion here, and I see two obvious ways to instantiate them.

Option #1 - Assign the Commands in the constructor.

public class Presenter : ObservableObject
{
public Presenter()
{
DoStuffCommand = new Command(DoStuff);
}

public ICommand DoStuffCommand { get; set; }

private void DoStuff()
{
// VM stuff
}

}


Option #2 - Instantiate Command in the getter

public class Presenter : ObservableObject
{
public ICommand RunCommand { get { return new Command(DoStuff); } }

private void DoStuff()
{
// VM stuff
}

}


Many view models are going to have a number of commands, and approach #2 avoids assigning all of these one by one in the constructor - when the commands action is not going to change, it's clearer to me having this action declared with the ICommand itself. On the other hand, this will create a new instance of Command every time the command fires, which is clearly less efficient memory wise than approach #1.

Does anyone have experience of this, and/or could give me an idea of whether this could impact performance noticeably? And is there a way to improve upon this, such as by manually destroying the Command objects?

Thanks!

Answer

An alternative to option #2 would be to have a backing field for it and ensures it only instantiates once:

private ICommand _doStuffCommand;
public ICommand DoStuffCommand =>
    _doStuffCommand = _doStuffCommand ?? new Command(DoStuff);

private void DoStuff()
{

}