Introduction
How many times did you write defensive code like this?
CalendarModel calendar = ...; int holidayCount = calendar.Holidays==null? 0 : calendar.Holidays.Count();
The good news is that C# 6.0 now has the Safe Navigation Operator (?.) more recognizable by its street name the Elvis operator. The bad news is that all versions prior to C# 6.0 do not.
The Code
Here is a small template class you can use to substitute it in older versions.
public class IsNull
{
public static O Substitute<I,O>(I obj, Func<I,O> fn, O nullValue=default(O))
{ if (obj == null) return nullValue; else return fn(obj); }
}
Let's write our previous example using this syntax.
CalendarModel calendar = ...; int holidayCount = IsNull.Substitute(calendar.Holidays, holidays=>holidays.Count(), 0);
Points of Interest
There is nothing wrong with using operators ? and ??. I assume they are quicker. But when performance is not an issue I prefer clearly declaring my intention in code to forcing those who read it after me to interpret it.