title: Simplifying RelayCommand/DelegateCommand in WPF MVVM ViewModels
body: <p>If you're doing MVVM and using commands, you'll often see ICommand properties on the ViewModel that are backed by private RelayCommand or DelegateCommand fields, like this example from the original MVVM article on <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx" rel="noreferrer">MSDN</a>:</p>
  
  <pre><code>RelayCommand _saveCommand;
  public ICommand SaveCommand
  {
      get
      {
          if (_saveCommand == null)
          {
              _saveCommand = new RelayCommand(param =&gt; this.Save(),
                  param =&gt; this.CanSave );
          }
          return _saveCommand;
      }
  }
  </code></pre>
  
  <p>However, this is a lot of clutter, and makes setting up new commands rather tedious (I work with some veteran WinForms developers who balk at all this typing).  So I wanted to simplify it and dug in a little.  I set a breakpoint at the first line of the get{} block and saw that it only got hit when my app was first loaded--I can later fire off as many commands as I want and this breakpoint never gets hit--so I wanted to simplify this to remove some clutter from my ViewModels and noticed that the following code works the same:</p>
  
  <pre><code>public ICommand SaveCommand
  {
      get
      {
          return new RelayCommand(param =&gt; this.Save(), param =&gt; this.CanSave );
      }
  }
  </code></pre>
  
  <p>However, I don't know enough about C# or the garbage collector to know if this could cause problems, such as generating excessive garbage in some cases.  Will this pose any problems?</p>