C# ?? operator

The ?? operator in C# called null-coalescing operator is used to define a default value for a nullable value types and reference types. It returns the left-hand operand if it is not null and returns right-hand operand if it is null.


// ?? operator example

. int? x = null;

int y = x ?? –1;

// Here the value of y will be –1.

int i = GetValue() ?? default(int);

Assigns the return value of the method to i if  return value is not null other wise it assigns default value

It can be used with reference type as follows

string s = GetStringValue(); // ?? also works with reference types. // Display contents of s, unless s is null, // in which case display "Unspecified". Console.WriteLine(s ?? "Unspecified");

Leave a reply

Why ask?