How useful is C#'s ?? operator?

后端 未结 13 2146
独厮守ぢ
独厮守ぢ 2020-12-08 07:43

So I have been intrigued by the ?? operator, but have still been unable to use it. I usually think about it when I am doing something like:

var x = (someObje         


        
13条回答
  •  清歌不尽
    2020-12-08 08:26

    I use the null-coalescing operator often when parsing strings into other data types. I have a set of extension methods that wrap things like Int32.TryParse and return a nullable int instead of exposing an output parameter to the rest of my code. Then I can parse a string and provide a default value if the parse failed, in a single line of code.

    // ToNullableInt(), is an extension method on string that returns null
    // if the input is null and returns null if Int32.TryParse fails.
    
    int startPage = Request.QueryString["start"].ToNullableInt() ?? 0;
    

提交回复
热议问题