Zze Zze - 3 months ago 20
C# Question

Why does *= resolve after +

Is there ever any cuircumstance where the following algorithms are not equal?

int var1 = 2;
int var2 = 5;
int var3 = 7;

// Scenario 1
var1 *= var2 + var3; // <-- 24

// Scenario 2
var1 = 2;
var1 *= (var2 + var3); // <-- 24


The reason I ask is because msdn site states the following:


These operators have higher precedence than the next section and lower precedence than the previous section.


However, from my testing, it seems that this is never the case? And that even without the brackets, it seems to resolve as if it had brackets.

I would of thought that the algorithms would be equal to:

// Scenario 1
var1 = var1 * var2 + var3; // <-- 17

//Scenario 2
var1 = var1 * (var2 + var3); // <-- 24




So what is meant by the msdn site and in what cases is their statement true?

C# fiddle for testing:

https://dotnetfiddle.net/Yt5ZBO

Answer

So what is meant by the msdn site and in what cases is their statement true?

It means exactly what it states: the sections are ordered from higher to lower precedence.

In their list *= operator (it's a single operator and its precedence has no relations with the precedence of either = or *) has lower precedence than the binary + operator.

So + is evaluated first.