C# Snippet Tutorial - The ?? Operator [Beginner]


Just the other day I came across a C# operator that I found particularly useful and decided to share it with everyone here at SOTC - the ?? operator. The briefest explanation is this: ?? is used a lot like the conditional operator (?:), except instead of any condition, it will only check if the value on the left is null. If it is not null, it returns the item on the left - otherwise it will return the thing on the right.

We'll start with a really simple example - reference types:
string myString = null;

string myOtherString = myString ?? "Something Else";

Console.WriteLine(myOtherString);

//Output: "Something Else"
 
Here we can see a string being assigned to null. Next we use the ?? operator to assign a value to myOtherString. Since myString is null, the ?? operator assigns the value "Something Else" to the string.

Let's get a little more complicated and see an example using nullable types.
int? myInt = null;

int anotherInt = myInt ?? 1234;

Console.WriteLine(anotherInt.ToString());

//Output: "1234"
 
The ?? operator is a great way to assign a nullable type to a non-nullable type. If you were to attempt to assign myInt to anotherInt, you'd receive a compile error. You could cast myInt to an integer, but if it was null, you'd receive a runtime exception.

Granted, you can do the exact same thing with the regular conditional operator:
int? myInt = null;

int anotherInt = myInt.HasValue ? myInt.Value : 1234;

Console.WriteLine(anotherInt.ToString());

//Output: "1234"
 
But, hey, that's a whole 22 extra characters - and really, it does add up when you are doing a lot of conversions from nullable to non-nullable types.

Comments