Is there a shorthand for the ternary operator in C#?
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";
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";
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.
上一篇: 如何将图片保存到iPhone照片库?
下一篇: C#中的三元运算符有没有简写?