While I was reading some C# code recentrly I noticed a very interesting use of the ?? operator. Here are some tips on how to make best use of it:
First lets clear out a standard use of the operator. If the expression on the left of the oeprator is not null, it will be used, otherwise the expression on the right will be evaluated and used. For example we expose a property that will override a string that we will use.
Then, we will try to get the string from a resource file and lastly we will use a default value. Here is how we can do that without the ?? operator to turn this code:
//User defined property.
string messageToPrint = UserMessage;
//If not fallback to Strings resource.
if (messageToPrint == null)
{
messageToPrint = Strings.ResourceMessage;
}
//Then fallback to a default message
if (messageToPrint == null)
{
messageToPrint = "Default Message";
}
Console.WriteLine(messageToPrint);
into something shorter:
//This can be shortened to: messageToPrint = UserMessage ?? Strings.ResourceMessage ?? "Default Message"; Console.WriteLine(messageToPrint); //Or even this: Console.WriteLine(UserMessage ?? Strings.ResourceMessage ?? "Default Message");
Also the null assignment operator can be used when assigning nullable value types to their non-nullable couterparts, also we can use the default keyword to help us if we do not mind what is the value we get:
Rect? nullableRect = null; //Skip the nullableRect.HasValue check and always get a value: Rect rectValue = nullableRect ?? default(Rect);
But then, here is the really evil use of the operator, i.e. an evil tip. This is the kind of thing you can use and if you understand it, it is ok but it will make the code unreadable for people that have no idea what this is. So it is good and bad at the same time
.
The standard lazy initialization of a property:
private object myProperty;
public object MyPropeperty
{
get
{
if (myProperty == null)
{
myProperty = this.CalculateMyProperty();
}
return myProperty;
}
}
Then the evil one-liner:
private object myProperty;
public object MyPropeperty
{
get
{
return myProperty ?? (myProperty = this.CalculateMyProperty());
}
}
Be sparingly evil and enjoy
.