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

后端 未结 13 1749
谎友^
谎友^ 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: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...).

提交回复
热议问题