C# Snippet Tutorial - The ?? Operator

Skill

C# Snippet Tutorial - The ?? Operator

Posted in:

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.

If you'd like to learn more about C# operators, I'd recommend checking out our two-parter series on operator overloading (part1, part2).

Carol
10/10/2008 - 08:50

Thanks for the post. This is a very handy feature that I've gotten in the habit of using.. it works especially well in templates where readability is a concern.

reply

Add Comment

Put code snippets inside language tags:
[language] [/language]

Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]

See here for supported languages.

Javascript must be enabled to submit anonymous comments - or you can login.

Sponsors