I’m in charge of creating coding standards and doing code reviews within my organization.
I came cross something within our source code like this:
object.Property = myVar1 = myVar2;
I don’t personally do this because I find it confusing. I see this and I want to read it like this:
object.Property = myVar1 == myVar2;
Now I know what it’s doing: It assigns myVar to myVar2 and then object.Property to myVar2. The coding standards document doesn’t explicitly state whether or not you can do this. It does state however to not assign variables within an if statement.
I guess my question is, is it bad enough style to draw out as a coding practice to not do it? I don’t like making code standard policies “just because I said so”
Edited to better explain my understanding
This so-called “chained assignment” is indeed controversial and there are quite a few questions on SO that address it.
It is a byproduct of assignment being an expression and not a statement, as you know, and to many people it can be confusing.
It many languages it is somewhat dangerous to novices. In languages where
[]is a constructor for empty array objects, writingmakes
aandbreference the same object. Novices tend to think it makes two separate empty arrays which can be filled independently. Not so! The C# equivalent,is arguably far less likely to occur, since
aandbwould be more likely to be initialized at the point of declaration, and such double assignments would be rarer, and furthermore C# programmers are more likely to see the obvious sharing in this case.A good rationale for instituting a prohibition against this is three-fold:
When you encounter error-prone constructs, you should avoid them because in avoiding them, you will never make that particular error. Granted, in C#, it may be far less error prone than in other languages.