Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '??' mean in C#? [duplicate]

Tags:

c#

.net

asp.net

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 ?? "";
like image 387
Troj Avatar asked Sep 22 '10 09:09

Troj


1 Answers

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.

E.g.:

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.

like image 56
djdd87 Avatar answered Sep 22 '22 06:09

djdd87