简体   繁体   中英

C# equivalent to JavaScript “OR assignment”

Does C# have an equivalent to JavaScript's assignment syntax var x = y || z; var x = y || z; ? In case you don't know, the result is not true/false . If y is defined, then it is assigned to x , otherwise z is assigned to x even if it is undefined.

Note that in JavaScript the variable still has to be declared: var test;

I think that you are looking for ?? operator.

MSDN Reference

var abc = blah ?? "default";

是的

这就是你要找的

var x = y ?? z;

In C# there's no such notion as variable not being defined. Such operator doesn't make sense in C#.

Unlike JavaScript, C# is not dynamic but static language so that such operation is impossible - a compilation error will occur.

Imagine you're writing this if :

if(pizzaPrice == hamburgerPrice)

Before declaring the variables first:

decimal pizzaPrice;
decimal hamburgerPrice;

An error will occur on compile-time.

Update: Even if the variables were declared it doesn't matter because C# does not support such a feature.

On the other hand, JavaScript is enforcing evaluation of the variable in if conditions by calling the ToBoolean method and if it's undefined or null it's equals to false and C# doesn't not contains such a behavior.

Look at this cool article: JavaScript pitfalls: null, false, undefined, NaN

But if you want to check if a variable is referencing to a null you can easily use the null coalescing operator "??" operator.

As the following:

var x = y ?? z;

Yes, there is: ??

string x = y ?? z;

Which basically calculates:

string x = y != null ? y : z

However, there are a few differences between Javascript and C#. As with JS, y and z must both be declared before hand. However, unlike JS, y and z must also be "assigned" in C# or a compiler error will be thrown as usual.

The operator requires a nullable type and it checks whether the first is null before returning the second. You can chain a whole bunch ( a ?? b ?? c ?? d ?? e ) if you want.

Note that a zero length string is not null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM