2

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!

BenMorel
  • 34,448
  • 50
  • 182
  • 322
elucid8
  • 1,412
  • 4
  • 19
  • 40

5 Answers5

7

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.

Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
2

You can use ??:

private int Foo(string val){
    this.name = val ?? "foo";
}
Artem Vyshniakov
  • 16,355
  • 3
  • 43
  • 47
2

Go with this

this.name = val ?? "foo";
Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157
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.

Bridge
  • 29,818
  • 9
  • 60
  • 82
J0HN
  • 26,063
  • 5
  • 54
  • 85
  • I've got to go with your answer, @J0HN since you mentioned that it wouldn't evaluate "falsy" values like JavaScript. – elucid8 Nov 15 '12 at 14:31
  • 1
    @elucid8, anyway, you should consider how an empty string should be treated. I've just recently faced a bug caused by using `str!=null` where `!String.IsNullOrEmpty(str)` should be. – J0HN Nov 15 '12 at 14:32
1

Yep, use ??:

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

Check Msdn for more information: ?? Operator

Uriil
  • 11,948
  • 11
  • 47
  • 68