What do two question marks together mean in C#?

前端 未结 18 1153
借酒劲吻你
借酒劲吻你 2020-11-22 03:41

Ran across this line of code:

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

What do the two question marks mean, is it some ki

18条回答
  •  太阳男子
    2020-11-22 04:34

    It's a null coalescing operator that works similarly to a ternary operator.

        a ?? b  => a !=null ? a : b 
    

    Another interesting point for this is, "A nullable type can contain a value, or it can be undefined". So if you try to assign a nullable value type to a non-nullable value type you will get a compile-time error.

    int? x = null; // x is nullable value type
    int z = 0; // z is non-nullable value type
    z = x; // compile error will be there.
    

    So to do that using ?? operator:

    z = x ?? 1; // with ?? operator there are no issues
    

提交回复
热议问题