TAGS :Viewed: 9 - Published at: a few seconds ago

[ When is it appropriate to use multiple destinations in a single assignment? ]

I occasionally see this:

int a = 1;
int b = 2;

a = b = 3;  //assign 3 to a and b.

I think it is not a good idea, but I do see it done. It seems like it is better to state

a = 3;
b = 3;

This way, it is clear to later readers that this is what is occurring.

Should assignments like these be avoided, or are there situations when such assignments would be preferred?

Edit After reviewing the comments and answer, I think a more accurate question is: Is IntA = IntB = 3 the same as splitting onto multiple lines?

The answer, for primitive types, is yes, it is the same. So to use or not to use is preference.

For reference types, the answer is no, it is not the same.

ref = ref = new Ref() results in two references to the same object.

ref = new Ref();
ref = new Ref();

results in two new objects. So it is legal to use if two object references is what your really intended. Beyond that, it is preference.

I see no other differences between the two.

Answer 1


There are situations when multiple assignments are definitely inappropriate. For example, the following should never be done:

decimal speed;
decimal distance;
speed = distance = 0M; // <<== This compiles, but it is very, very wrong.

There are situations when multi-assignments provide for better readability - specifically, when you are assigning the same object instance to two variables before going into an algorithm that may or may not leave them "pointing" at the same object:

// You can do this
MyClass smallest;
MyClass largest;
smallest = new MyClass();
largest = smallest;
// However, this conveys the idea slightly better:
MyClass smallest;
MyClass largest;
smallest = largest = new MyClass();

Though technically it is not the same, a related situation when multi-assignment provides for better readability is when you cache a result:

MyClass res = cached ?? (cached = Compute());

In this case the assignment of Compute() to res also changes cached, unless cached is non-null to begin with.