Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "??" operator for? [duplicate]

I was wondering about ?? signs in C# code. What is it for? And how can I use it?

What about int?? Is it a nullable int?

See also:

?? Null Coalescing Operator —> What does coalescing mean?

like image 742
Ante Avatar asked May 05 '09 23:05

Ante


4 Answers

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

The result of the expression 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.

like image 180
Jon Skeet Avatar answered Oct 23 '22 20:10

Jon Skeet


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;
like image 45
BFree Avatar answered Oct 23 '22 19:10

BFree


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
like image 12
JaredPar Avatar answered Oct 23 '22 21:10

JaredPar


It's the new Null Coalesce operator.

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.

You can read about it here: http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx

like image 8
Scott Ferguson Avatar answered Oct 23 '22 19:10

Scott Ferguson