What is the "??" operator for?
This question already has an answer here:
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
上一篇: 什么? 运营商意味着在C#?
下一篇: 是什么 ”??” 运营商的?