What is the "??" operator for?

This question already has an answer here:

  • What do two question marks together mean in C#? 16 answers

  • It's called the "null coalescing operator" and works something like this:

    Instead of doing:

    int? number = null;
    int result = number == null ? 0 : number;
    

    You can now just do:

    int result = number ?? 0;
    

    It's the null coalescing operator. It was introduced in C# 2.

    The result of the expression a ?? b a ?? b is a if that's not null, or b otherwise. b isn't evaluated unless it's needed.

    Two nice things:

  • The overall type of the expression is that of the second operand, which is important when you're using nullable value types:

    int? maybe = ...;
    int definitely = maybe ?? 10;
    

    (Note that you can't use a non-nullable value type as the first operand - it would be pointless.)

  • The associativity rules mean you can chain this really easily. For example:

    string address = shippingAddress ?? billingAddress ?? contactAddress;
    
  • That will use the first non-null value out of the shipping, billing or contact address.


    That is the coalesce operator. It essentially is shorthand for the following

    x ?? new Student();
    x != null ? x : new Student();
    

    MSDN Documentation on the operator

  • http://msdn.microsoft.com/en-us/library/ms173224.aspx
  • 链接地址: http://www.djcxy.com/p/53828.html

    上一篇: 什么? 运营商意味着在C#?

    下一篇: 是什么 ”??” 运营商的?