Search code examples
c#javascriptlanguage-featuresnull-check

Does C# Have An Operation Similar to JavaScript's || Setter?


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!


Solution

  • 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.