Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Poor Man’s Elvis Operator

0.00/5 (No votes)
16 Jun 2016 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here