Question

Does C# have a similar operation to JavaScript's || setter?

For example, in JavaScript, if I want to check if a value is null and set a default, I can do something like this:

function foo(val){
    this.name = val || "foo";
}

But, when I want this functionality in C# I have to go this route:

public Foo(string val)
{
    this.name = (string.IsNullOrEmpty(val) ? "foo" : val);
}

I know this is petty and that beggars can't be choosers but, if at all possible, I'd like to avoid getting any answers that involve crazy hacks or extension methods. I'm fine with using the ternary operator, but I was just curious if there was a language feature I'd missed.

Update:

Great answers all around, but J0HN and Anton hit it on the head. C# doesn't do "falsy" values like JavaScript would in the example above, so the ?? operator doesn't account for empty strings.

Thanks for your time and the great responses!

Was it helpful?

Solution 2

There is a ?? operator that essentially is the same as COALESCE operator in SQL:

int? a = null; //int? - nullable int
int q = a??1; // q is set to one;

However, ?? does not check the string for emptiness, so it does not share the same meaning as javascript's ||, which treats empty strings as false as well.

OTHER TIPS

There's a null-coalescing operator in C#, though it can't handle all the quirkiness of JavaScript:

this.name = val ?? "foo";

Since an empty string is false in JavaScript, this C# code will behave differently from its JS counterpart.

You can use ??:

private int Foo(string val){
    this.name = val ?? "foo";
}

Go with this

this.name = val ?? "foo";

Yep, use ??:

    private int Foo(string val){
        this.name = val ?? "foo";
    }

Check Msdn for more information: ?? Operator

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top