What does '??' mean in C#?
Possible Duplicate:
What do two question marks together mean in C#?
I'm trying to understand what this statment does: what does "??" mean? is this som type if if-statment?
string cookieKey = "SearchDisplayType" + key ?? "";
It's the Null Coalescing operator. It means that if the first part has value then that value is returned, otherwise it returns the second part.
Eg:
object foo = null;
object rar = "Hello";
object something = foo ?? rar;
something == "Hello"; // true
Or some actual code:
IEnumerable<Customer> customers = GetCustomers();
IList<Customer> customerList = customers as IList<Customer> ??
customers.ToList();
What this example is doing is casting the customers as an IList<Customer>
. If this cast results in a null, it'll call the LINQ ToList
method on the customer IEnumerable.
The comparable if statement would be this:
IEnumerable<Customer> customers = GetCustomers();
IList<Customer> customersList = customers as IList<Customer>;
if (customersList == null)
{
customersList = customers.ToList();
}
Which is a lot of code compared to doing it within a single line using the null-coalescing operator.
It's this. Well, not really.
Actually, it's this. And this, this, this and this, to name a few. I used almighty Google to find them, since SO has no function to search in the answers (correct?), thus making it hard to find duplicates to this kind of question. Well, for the future, use this as reference. ;-)
It's called the null-coalescing operator. It's basically the same as
int? nullableDemoInteger;
// ...
int someValue = nullableDemoInteger ?? -1;
// basically same as
int someValue = nullableDemoInteger.HasValue ? nullableDemoInteger.Value : -1;
// basically same as
int someValue;
if(nullableDemoInteger.HasValue)
someValue = nullableDemoInteger.Value;
else
someValue = -1;
It's the null-coalescing operator. In this case it's roughly equivalent to:
string cookieKey;
string temp = "SearchDisplayType" + key;
if (temp == null)
cookieKey = "";
else
cookieKey = temp;
And, since "SearchDisplayType" + key
can never be null
, this is exactly equivalent to:
string cookieKey = "SearchDisplayType" + key;
链接地址: http://www.djcxy.com/p/53832.html
上一篇: 什么? 在C#中是什么意思?
下一篇: 什么是'??' 在C#中是什么意思?