#967 – Assigning a Value to a Variable

You store a value in a variable, or assign the value, use the = operator.  The = operator is known as the simple assignment operator.

When using the simple assignment operator, the value of the right operand is computed and the result is stored in the variable that appears as the left operand.

myInteger = 5;       // 5 stored in myInteger
myInteger = 8 + 3;   // 11 stored in myInteger

The right operand is an expression containing one or more operands and operators that is evaluated to determine a resulting value.  Operands within the expression can be constants, variables, properties or the results of function calls.

            myInteger = (12 + (8 * TripleThisNumber(2))) / myDog.Age;

The left side of an assignment statement can specify a variable, a property, or an indexer access.

            myDog.Age = 12;
            myArray[2] = 42;

#516 – The Assignment Operator is Right-Associative

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;