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