In your opinion what is more readable: ?? (operator) or use of if's

后端 未结 13 1751
谎友^
谎友^ 2021-01-21 07:05

I have a method that will receive a string, but before I can work with it, I have to convert it to int. Sometimes it can be null and I ha

13条回答
  •  爱一瞬间的悲伤
    2021-01-21 07:17

    In this case the earlier is more readable as its a trivial example. **However in your case they are not equivalent, as the ?? isn't the same as string.IsNullOrEmpty **

    The latter would be better in cases where the if was complex. I'd say horses for courses. Just depends on the audience. Try and keep it simple.

    public int doSomeWork(string value)
    {
      return int.Parse(value ?? "0");
    }
    
    
    
    public int doSomeWork(string value)
    {
       if(value == null)
          value = "0";
        int SomeValue = int.Parse(value);
        return SomeValue;
    }
    

提交回复
热议问题