简体   繁体   中英

Output (Nullable Types in C#)

In c# (nullable types)

int a = 10;
int? b = 20;
int? c = null;

System.Console.WriteLine( a+c??b );

Output is : 20

if (c??b +a) then Output is 30

I don't understand why ..

It's just a matter of precedence.

This:

System.Console.WriteLine(a + c ?? b);

is equivalent to:

System.Console.WriteLine((a + c) ?? b);

a + c is null (because c is null), therefore 20 is printed (the value of b )

Whereas this:

System.Console.WriteLine(c ?? b + a);

is equivalent to:

System.Console.WriteLine(c ?? (b + a));

c is null, therefore the RHS ( b + a ) is evaluated, and that's 30.

c??b + a is evaluated as

 c?? (b+a)

or slightly expanded

 c == null ? b + a : c

or if we substitute with the actual values

 null == null ? 20 + 10 : null) 

whereas a +c??b is evaluated as

 (a+c)??b

or if we expand slightly

 (a + c) == null ? b : c+a

or if we substitute with the actual values

 (10 + null) == null ? 20 : 10 + null

which again can be shortened to

 null == null ? 20 : null

the addition operator for nullable types always return null if at least one of the operands are null

When you write:

  System.Console.WriteLine( a+c??b );

It will effectively evaluate as:

        int? temp = a + c;
        System.Console.WriteLine(temp ?? b);

The "temp" above is null, so you get the result of b .

Check here: ECMA-334: 14.2.1 Operator precedence and associativity

The order of precedence of Null Coalescing operator (??) is very less than that of '+'. So, '+' is always evaluated first.

In your case,

int a = 10;
int? b = 20;
int? c = null;

a+c??b evaluates as (a+c)??b = (10+null)??20 = null??20 = 20

c??b+a evaluates as c??(b+a) = null??(10+20) = (10+20) = 30

Since c is null then the answer is b! That's what your double ? do.

The ?? operator is used to check for nulls. It returns either the value in question, or a fallback if it is null.

c ?? b c ?? b means "c, unless c is null, in which case b".

c ?? b + a c ?? b + a checks c, and sees that it is null, and uses b (20) instead. It then adds a (10) to get 30.*

a + c ?? b a + c ?? b seems to be applying the ?? to a + c rather than just to c, resulting in the whole thing being replaced with b (20).

*Not sure about order of operations in this case, it might be using (b + a) due to c being 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