Does C# have something like the JavaScript if or value syntax?
For example, I know you can do this in JavaScript:
var test = someValue || thisValue;
if someValue is undefined, false, or empty string, then test becomes thisValue. However, I've never seen a way to do this in C# other than a traditional if, or inline if.
NullCoalesce
var test = someValue ?? thisValue;
However, C# doesn't do weird JavaScript falsey behaviors.
The short circuit evaluation in C# is more pertinent in evaulating bools:
private bool EvaluateA()
{
return true;
}
private bool EvaluateB()
{
return false;
}
public static int main()
{
Console.Write(EvaluateA() || EvaluateB()); // EvaluateB is never called
}
Its called the null-coalescing operator.
String someValue = null;
var thisValue = "Foo";
var test = someValue ?? thisValue;
// test will be == "Foo"
As mentioned in the comments, this doesn't work for empty strings, "false", etc. What you can do in C# is write an extension method to do that, if you really want to:
public static class MyStringThing {
public static String FixErUp(this String s1, String s2) {
if (String.IsNullOrWhiteSpace(s1) || s1.Equals("false"))
return s2;
return s1;
}
}
to be used like so:
String someValue = "false";
var thisValue = "Foo";
var test = someValue.FixErUp(thisValue);
// test will be == "Foo"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With