Welcome to MSDN Blogs Sign in | Join | Help

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>";

 

Published Thursday, November 03, 2005 3:03 PM by abhinaba
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: C# 2.0: The all new ?? operator

Thursday, November 03, 2005 5:34 AM by ric hardacre
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 ""?

# re: C# 2.0: The all new ?? operator

Sunday, November 06, 2005 11:51 PM by abhinaba
It works only for null and hence only for reference and nullable types and NOT for value types....

# re: C# 2.0: The all new ?? operator

Monday, November 07, 2005 5:41 PM by asdf
I take it that ?? doesn't evaluate the rhs unless it is null (unlike the GetValueOrUseDefault example).

# re: C# 2.0: The all new ?? operator

Tuesday, November 08, 2005 12:18 AM by abhinaba
you are right, rhs is evaluated only when lhs is null

# re: C# 2.0: The all new ?? operator

Thursday, December 07, 2006 4:20 AM by s

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

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

# re: C# 2.0: The all new ?? operator

Saturday, July 07, 2007 4:51 AM by .netdev

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

# c new operator

Wednesday, June 11, 2008 6:02 AM by c new operator

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker