1

Background

In PHP there is a shorthand for the ternary operator:

$value = "";
echo $value ?: "value was empty"; // same as $value == "" ? "value was empty" : $value;

In JS there's also an equivalent:

var value = "";
var ret = value || "value was empty"; // same as var ret = value == "" ? "value was empty" : value;

But in C#, there's (as far as i know) only the "full" version works:

string Value = "";
string Result = Value == string.Empty ? "value was empty" : Value;

So my question is: Is there a shorthand for the ternary operator in C#, and if not, is there a workaround?

Research

I found the following questions, but they're referring to use the ternary operator as shorthand to if-else:

shorthand If Statements: C#

Benefits of using the conditional ?: (ternary) operator

And this one, but it's concerning Java:

Is there a PHP like short version of the ternary operator in Java?

What I have tried

Use the shorthand style of PHP (Failed due to syntax error)

string Value = "";
string Result = Value ?: "value was empty";

Use the shorthand style of JS (Failed because "The || operator is not applicable to string and string.")

string Value = "";
string Result = Value || "value was empty";
  • but the ternary operator is short hand. Is it really that difficult to type one line of code? – Liam Sep 12 '17 at 10:43
  • 2
    Your examples exploit the principle of truthy & falsey values, a concept that does not (by default) exist in strongly typed C#. – Alex K. Sep 12 '17 at 10:43
  • `value || "value was empty"` is not a short hand for a ternary operator. It's a logic statement. This isn't the same thing. Javascript just tends to coerce values because it's not strongly typed, unlike c# – Liam Sep 12 '17 at 10:44

2 Answers2

16

There is no shorthand for when the string is empty. There is a shorthand for when the string is null :

string Value = null;
string Result = Value ?? "value was null";
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
6

The coalesce ?? operator works only on null, but you could "customize" the behavior with an extension method:

public static class StringExtensions
{
    public static string Coalesce(this string value, string @default)
    {
        return string.IsNullOrEmpty(value)
            ? value
            : @default;
    }
}

and you use it like this:

var s = stringValue.Coalesce("value was empty or null");

But I don't think it is much better than the ternary.

Note: the @ allows you to use reserved words as variable names.

Val
  • 1,920
  • 1
  • 11
  • 14