Don’t understand pre decrement operator behavior with Nullable type

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…

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)