Why do assignment statements return a value?

Viewed 29711

This is allowed:

int a, b, c;
a = b = c = 16;

string s = null;
while ((s = "Hello") != null) ;

To my understanding, assignment s = ”Hello”; should only cause “Hello” to be assigned to s, but the operation shouldn’t return any value. If that was true, then ((s = "Hello") != null) would produce an error, since null would be compared to nothing.

What is the reasoning behind allowing assignment statements to return a value?

14 Answers

I like using the assignment return value when I need to update a bunch of stuff and return whether or not there were any changes:

bool hasChanged = false;

hasChanged |= thing.Property != (thing.Property = "Value");
hasChanged |= thing.AnotherProperty != (thing.AnotherProperty = 42);
hasChanged |= thing.OneMore != (thing.OneMore = "They get it");

return hasChanged;

Be careful though. You might think you can shorten it to this:

return thing.Property != (thing.Property = "Value") ||
    thing.AnotherProperty != (thing.AnotherProperty = 42) ||
    thing.OneMore != (thing.OneMore = "They get it");

But this will actually stop evaluating the or statements after it finds the first true. In this case that means it stops assigning subsequent values once it assigns the first value that is different.

See https://dotnetfiddle.net/e05Rh8 to play around with this

Related