How useful is C#'s ?? operator?

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

    Just as an FYI, the ternary operator generates a different sequence of IL from the null coalescing operator. The first looks something like such:

    // string s = null;
    // string y = s != null ? s : "Default";
        ldloc.0
        brtrue.s notnull1
        ldstr "Default"
        br.s isnull1
        notnull1: ldloc.0
        isnull1: stloc.1
    

    And the latter looks like such:

    // y = s ?? "Default";
        ldloc.0
        dup
        brtrue.s notnull2
        pop
        ldstr "Default"
        notnull2: stloc.1
    

    Based on this, I'd say the null coalescing operator is optimized for its purpose and is not just syntactic sugar.

提交回复
热议问题