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

确保非空值返回的三种方法
本文介绍了三种确保变量非空返回的方法:通过条件语句、条件表达式及空合并运算符。这些方法适用于.NET平台中DelegateCommand<object>类型的初始化,确保每次调用都能返回一个非空实例。

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值