Poor Man’s Elvis Operator






4.91/5 (7 votes)
Poor Man’s Elvis Operator
Introduction
How many times did you write defensive code like this?
CalendarModel calendar = ...; // Somehow create 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 = ...; // Somehow create calendar.
int holidayCount = IsNull.Substitute(calendar.Holidays, holidays=>holidays.Count(), 0); // 0 is obsolete.
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.