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!

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It is worth mentioning that if val is an empty string, the OP will not achieve the desired result.
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.

2 Comments

I've got to go with your answer, @J0HN since you mentioned that it wouldn't evaluate "falsy" values like JavaScript.
@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.
2

You can use ??:

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

1 Comment

this isn't the same as Foo.
2

Go with this

this.name = val ?? "foo";

Comments

1

Yep, use ??:

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

Check Msdn for more information: ?? Operator

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.