Switch On The Code RSS Button - Click to Subscribe
Sep
23

C# Snippet Tutorial - The ?? Operator

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 a conditional (?:), 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).



Posted in C#, All Tutorials by The Reddest |

One Response

  1. Carol Says:

    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.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

Powered by WP Hashcash