EDIT: This has been confirmed as a bug in the compiler by the team. It is fixed in Roslyn. As a workaround, use a cast (int?)(--i)
to stop the bug appearing, or don't explicitly cast it to a Nullable<int>
in the first place.
The first code block generates the following in reflector:
int? nullable3;
int? nullable = 1;
int num = 1;
int? nullable2 = nullable;
nullable2 = nullable = nullable2.HasValue
? new int?(nullable2.GetValueOrDefault() + 1)
: ((int?) (nullable3 = null));
int num2 = --num;
nullable = nullable2.HasValue
? new int?(nullable2.GetValueOrDefault() - num2)
: ((int?) (nullable3 = null));
Console.WriteLine("Without Nullable<int> n = {0}", nullable);
The second the following:
nullable = 1;
num = 1;
nullable2 = nullable;
nullable2 = nullable = nullable2.HasValue
? new int?(nullable2.GetValueOrDefault() + 1)
: ((int?) (nullable3 = null));
num2 = --num;
nullable = nullable2.HasValue
? new int?(nullable2.GetValueOrDefault() - --num)
: null;
Console.WriteLine("With Nullable<int> n = {0}", nullable);
They're more or less the same, up to the assignment to nullable
. It's running --num
twice, causing it to run 2 - -1
, resulting in 3.
It also does the same with expressions like i = ~i
, but not with method call expressions...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…