Updated Mar 6 2020 :: by Alex Yumashev

Here's a little C# hack I'd like to share, might be really useful to other devs too since it's a very common pain in all languages, not just .NET.

We all love the ternary operator x ? y : z and often use it to concatenate strings. Like this, for example:

var sql = "SELECT x FROM y WHERE z " + (condition ? "AND xyz" : "");

But more often like this - this is in the markup, in the views:

<div class='someclass @(condition ? "anotherclass" : "")'>

(not only C#-ers are doing that, everyone does)

And this stupid part : "" has been driving me nuts for many years.

And not just me, Microsoft has been getting issues on GitHub - "please make a ternary operator without the right side in C# 9" (I'm not sure that's a good idea though). And a Google search for "ternary operator without else site:stackoverflow.com" produces as many as 62 thousand (!) results from Stackoverflow only, people complain in all languages, even the dynamic ones like JavaScript and Python.

So here's how we solve this problem in C# - let's create an extension method for bool called .Then

public static T Then<T>(this bool value, T result)
{
    return value ? result : default (T);
}

(No need to show off with a generic, you can make it a simple "string", but it's prettier this way)

And your life instantly gets better. Check out this cool code:

<div class='someclass @condition.Then("anotherclass")'>

'C# Ternary Operator with no "Else"' was written by Alex Yumashev
Alex Yumashev
Alex has founded Jitbit in 2005 and is a software engineer passionate about customer support.


Subscribe comments