C# 2.0: The all new ?? operator

Thanks to James Manning’s blog I remembered the new ?? operator introduced in C#2.0 and that very few people seem to use it.

This new ?? operator is mainly used for nullable types but can also be used with any reference type.

Use with nullable type

In case you are converting a nullable type into a non-nullable type using code as follows

int? a = null;

// …

int e = (int)a;

You will land into trouble since a is null and an System.InvalidOperationException will be thrown. To do this correctly you first need to define what is the value of int which you’ll consider as invalid (I choose -1) and then use any of the following expressions.

int? a = null;

// …

int e = (a != null) ? (int)a : -1;

int f = a.HasValue ? a.Value : -1;

int g = a.GetValueOrDefault(-1);

This is where the ?? operator comes into play. Its a short hand notation of doing exactly this and you can just use

int? a = null;

// …

int c = a ?? -1;

Use with any reference type

In code many times we compare reference to null and assign values based on it. I made a quick search on some code and found the following code used to write function arguments to a log file

string localPath = (LocalPath == null ? “<null>” : LocalPath);

This can be coded easily using

string localPath = LocalPath ?? “<null>”;


Comments (7)

  1. ric hardacre says:

    very nice, if only someone had’ve thought of that when they thought of ?: all them years ago!

    question, does it specifically check for null or does it also work for 0 and ""?

  2. It works only for null and hence only for reference and nullable types and NOT for value types….

  3. asdf says:

    I take it that ?? doesn’t evaluate the rhs unless it is null (unlike the GetValueOrUseDefault example).

  4. you are right, rhs is evaluated only when lhs is null

  5. s says:

    that’s the point! but notice that u can use it like:

    string server = server1 ?? server2 ?? "defaultServer";

  6. .netdev says:

    Does it work checking for null in SqlDataReader? Can I use it to check for null instead of DBNull.Value?