How useful is C#'s ?? operator?

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

    I use it in working with methods that can return null under normal operation.

    for example, lets say that I have a container class that has a Get method that returns null if the container doesn't contain a key (or maybe null is a valid association). Then I might do something like this:

    string GetStringRep(object key) {
        object o = container.Get(key) ?? "null";
        return o.ToString();
    }
    

    clearly, these two sequences are equivalent:

    foo = bar != null ? bar : baz;
    foo = bar ?? baz;
    

    The second is merely more terse.

提交回复
热议问题