Suiko6272
Suiko6272

Reputation: 117

DelegateCommand creation, in Constructor or in Property

I've seen multiple examples of DelegateCommands being created in either the constructor or within the property itself. I'm wondering if there is any advantage of doing it in the constructor as I've been doing it within the property to keep track of it easier.

(Using Prism, Silverlight4 and SimpleMVVM Toolkit in my case)

    private DelegateCommand _cmdLogin;
    public DelegateCommand CmdLogin
    {
        get
        {
            if (_cmdLogin == null)
            {
                _cmdLogin = new DelegateCommand(this.Login, this.CanLogIn);
            }
            return _cmdLogin;
        }
    }

VS

    public LoginViewModel()
    {
        this.LoginCommand = new DelegateCommand(this.Login, this.CanLogin);
    }
    public DelegateCommand LoginCommand { get; set; }

Upvotes: 0

Views: 324

Answers (1)

Anton
Anton

Reputation: 7719

I have had the same thought as you Suiko6272 on this.

I ended up going with your second solution in the end. however i did use this mechanism in my property gets for quite a while

private DelegateCommand _cmdLogin;
public DelegateCommand CmdLogin
{
    get { return _cmdLogin??(_cmdLogin = new DelegateCommand(this.Login, this.CanLogIn));}
}

The above code lazy loads the delegatecommand and is only 1 line of code.

I ended up going with your second solution because it is the clearest/easiest for other coders to read.

Upvotes: 1

Related Questions