tip: C# check nullity, assignment and return in one statement

It is a common practise to check if a variable is null, and if it is null, assign some value to it, then return the assigned variable, or just return the cached value if the variable is not nulll..

 

suppose you have  a field called m_mydelegateCommand, and you want to ensure non-null value is returned. 

 

you may do this 

 

    private DelegateCommand<object> m_mydelegateCommand;
    public DelegateCommand<object> MyDelegateCommand {
      get
      {
        if (m_mydelegateCommand == null) m_mydelegateCommand = new DelegateCommand<object>(MyDelegateCommandExecuted);
        return m_mydelegateCommand;
      }
    }
 

With the help of conditional expression, you may do this.

 

    private DelegateCommand<object> m_mydelegateCommand;
    public DelegateCommand<object> MyDelegateCommand {
      get
      {
        return m_mydelegateCommand != null ? m_mydelegateCommand : m_mydelegateCommand = new DelegateCommand<object>(MyDelegateCommandExecuted);

      }
    }
 

With the help from Nullale operator ??, you can do even simpler as this:

 

    private DelegateCommand<object> m_mydelegateCommand;
    public DelegateCommand<object> MyDelegateCommand {
      get
      {
        return m_mydelegateCommand ?? (m_mydelegateCommand =  new DelegateCommand<object>(MyDelegateCommandExecuted));
      }
    }
 

 

 

你可能感兴趣的:(C#)