How useful is C#'s ?? operator?

后端 未结 13 2008
独厮守ぢ
独厮守ぢ 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:27

    The most useful is when dealing with nullable types.

    bool? whatabool;
    //...
    bool realBool = whatabool ?? false;
    

    without ?? you would need to write the following, which is much more confusing.

    bool realbool = false;
    if (whatabool.HasValue)
        realbool = whatabool.Value;
    

    I find this operator very useful for nullable types, but other than that I don't find myself using it very much. Definitely a cool shortcut.

提交回复
热议问题