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

后端 未结 13 1720
谎友^
谎友^ 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:28

    Actually you could refactor to

    var value = 0;
    int.TryParse(yourString, out value);

    either way you always have a valid integer (if that is the goal)

    0 讨论(0)
  • 2021-01-21 07:28

    You can do it your way? Cool!

    If is definitely more readable, unless everyone is more of a C# wonk than me.

    0 讨论(0)
  • 2021-01-21 07:30

    [Assuming you only need to check for null, and not empty string also, as others have pointed out]

    The semantic difference between the two is that ?? is an expression, while if is a statement. An expression says "perform a calculation and return a result", exactly the semantics you seek. More work has to be done to allow an if statement to express the same semantics; beyond that, the if leaves room for more logic than the calculation, room you don't need.

    You should use the ?? operator because it expresses exactly the desired intent.

    0 讨论(0)
  • 2021-01-21 07:31

    Why parse the string "0" just to get integer value 0? I definitely prefer this:

    public int doSomeWork(string value) {
       int someValue;
       if (String.IsNullOrEmpty(value)) {
          someValue = 0;
       } else {
          someValue = Int32.Parse(value);
       }
    }
    
    0 讨论(0)
  • 2021-01-21 07:32

    Why not just use TryParse()?

    public int doSomeWork(string stringValue)
    {
        int value;
        int.TryParse(stringValue, out value);
    
        return value;
    }
    

    The above code will return 0 if the value is anything but an actual number.

    So in my opinion, my example is the most readable. I try to parse the int and return it. No coalesce operator, and no string methods are used. This method also handles the exceptions that might be thrown when parsing (unless you WANT the exceptions...).

    0 讨论(0)
  • 2021-01-21 07:37

    Another solution is

    int someValue = string.IsNullOrEmpty(value) ? 0 : int.Parse(value);

    0 讨论(0)
提交回复
热议问题