Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# inline if or value syntax

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.

like image 536
farina Avatar asked Mar 11 '26 23:03

farina


2 Answers

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
}
like image 71
Joe Avatar answered Mar 14 '26 11:03

Joe


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"
like image 23
Chris Shain Avatar answered Mar 14 '26 13:03

Chris Shain