#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;
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #516 – The Assignment Operator is Right-Associative

  1. 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()); }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: