Null-conditional operator evaluates to bool not to bool? as expected

前端 未结 2 2137
误落风尘
误落风尘 2021-02-05 04:52

I\'ve just upgraded from VS 2010 to 2015. I like the new null-conditional operator which is also known as null-propagation. This enables to simplify your code, for example:

2条回答
  •  甜味超标
    2021-02-05 05:38

    If you use this code, and hover over x, you see that x is a int?:

    var x = text?.IndexOf("Foo", StringComparison.CurrentCultureIgnoreCase);
    bool contains = x >= 0;
    

    So the typing is still correct.

    Then lets look into x >= 0: that is a int? >= int. Appearantly there is an operator between the nullable and non-nullable structs. That is why it works.

    If you look at the IL, you will see it actually calls HasValue and GetValueOrDefault(). I guess there is an operator doing this, but I couldn't find it in the reference source, so it should be in the CLR or compiler:

    instance !0 valuetype [mscorlib]System.Nullable`1::GetValueOrDefault()
    
    ...
    instance bool valuetype [mscorlib]System.Nullable`1::get_HasValue()
    

提交回复
热议问题