简体   繁体   中英

what is the c# rule about this inline assignment

I was expecting the result to be 0

dotnetfiddler demo

using System;

public class Program
{
    public static void Main()
    {
        int value = 5;
        value += (value += 5) > 5 ? -value : +value;

        Console.WriteLine(value);
    }
}
  1. value start at 5
  2. value increase to 10
  3. the coalesce detect that it is higher than 5
  4. it return -10

since value was detected to be higher than 5, which mean it had the value of 10 in this case, i was expecting 10 += -10

what is happening is 5 += -10

what define this behavior?

I believe it functions like so:

int value = 5;
value += //5 is stored here for the calculation
   (value += 5) // 5 is modified to 10
     > 5 
     ? -value //-10 
     : +value; //10

so you get 5 - 10 = -5

Further reading: MSDN

Lets look at the emitted IL in Release Mode:

Program.Main:
IL_0000:  ldc.i4.5    // Load 5
IL_0001:  stloc.0     // Store value
IL_0002:  ldloc.0     // Load value
IL_0003:  dup         // Create a duplicate of value (5)
IL_0004:  ldc.i4.5    // Load 5
IL_0005:  add         // Add 5 to variable. Now value == 10
IL_0006:  dup         // Duplicate value.
IL_0007:  stloc.0     // Store value (10)
IL_0008:  ldc.i4.5    // Load 5
IL_0009:  bgt.s       IL_000E // Check value (10) > 5. If true go to IL_000E
IL_000B:  ldloc.0     // value
IL_000C:  br.s        IL_0010
IL_000E:  ldloc.0     // Load value (10)
IL_000F:  neg         // Negate value (-10)
IL_0010:  add         // -10 + 5 = -5
IL_0011:  stloc.0     // Store -5 in value
IL_0012:  ldloc.0     // value
IL_0013:  call        System.Console.WriteLine // Print value
IL_0018:  ret  

This kind of code is confusing. Try avoiding it at all costs.

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