Click here to Skip to main content
15,888,527 members
Articles / Programming Languages / C#
Tip/Trick

Poor Man’s Elvis Operator

Rate me:
Please Sign up or sign in to vote.
4.91/5 (7 votes)
16 Jun 2016CPOL 14.3K   2   4
Poor Man’s Elvis Operator

Introduction

How many times did you write defensive code like this?

C++
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.

C++
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.

C++
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Wischner Ltd
United Kingdom United Kingdom
Writing code since 1982 and still enjoying it.

Comments and Discussions

 
QuestionI never loved elvis Pin
LeckhamptonSteve21-Jun-16 0:38
LeckhamptonSteve21-Jun-16 0:38 
QuestionIts not restricted to C#6 per se Pin
TrendyTim20-Jun-16 18:15
TrendyTim20-Jun-16 18:15 
GeneralMy vote of 5 Pin
Imagiv18-Jun-16 1:28
Imagiv18-Jun-16 1:28 
Short, but informative. Had no idea you could use such an operator and I've been playing with C# for a while now haha.
PraiseThanks for sharing. Pin
Slacker00716-Jun-16 23:46
professionalSlacker00716-Jun-16 23:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.