#516 – The Assignment Operator is Right-Associative
February 9, 2012 2 Comments
An expression can contain more than one assignment operator. If this is the case, the assignments are evaluated from right to left. Consider the code fragment below.
int x = 12; int z = 24; int i = x = z;
Because the assignments are done from right to left, the variable x is first assigned the value that is stored in z (24). At this point, both x and z have the value of 24.
Next, i is assigned the value that is the result of the first assignment (24). At this point, x, z and i now all have the value of 24.
Because this behavior can be a little confusing, it’s generally preferable to do each assignment on a separate line.
int x = 12; int z = 24; x = z; int i = x;
A syntactical sugary “trick” I use to ensure a field/var is never null, it sort of takes advantage of the knowledge of right-associative since _ints will be assigned before it is returned.
IList _ints;
public IList Ints
{
get { return _ints = (_ints ?? new List()); }
}
Nice