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
- Anonymous
November 02, 2005
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 ""? - Anonymous
November 06, 2005
It works only for null and hence only for reference and nullable types and NOT for value types.... - Anonymous
November 07, 2005
I take it that ?? doesn't evaluate the rhs unless it is null (unlike the GetValueOrUseDefault example). - Anonymous
November 07, 2005
you are right, rhs is evaluated only when lhs is null - Anonymous
December 06, 2006
that's the point! but notice that u can use it like:string server = server1 ?? server2 ?? "defaultServer"; - Anonymous
July 06, 2007
Does it work checking for null in SqlDataReader? Can I use it to check for null instead of DBNull.Value? - Anonymous
June 10, 2008
PingBack from http://alessandra.eurovideosite.com/cnewoperator.html