I've seen code where the developer assigns properties or local variables from an if statement after performing some method call.
Example:
void SomeMethod()
{
MyObject myObject;
if ((myObject = DoSomething()) != null)
{
//Do some business logic
}
}
I think it gets very messy when a lot of these assignments are happening, or there is more going on in the if-statement, such as accessing an array.
I personally prefer something like this:
void SomeMethod()
{
MyObject myObject = DoSomething();
if (myObject != null)
{
//Do some business logic
}
}
Is there any benefit of the first piece of code over the second example? Any miniscule efficiency gains or anything? I want to know if I'm missing something.
A large piece of the code set is becoming nested with this style of code which I believe is less readable.
There is no performance implications to this change - it is a matter of personal preference. This works because an assignment is a value-producing expression, which can be used in comparison or other expressions. The idea is to "fold" the assignment into the header of a conditional, essentially saving a line of code.
Although this makes no difference with a single if
(the number of lines does not change) it does make a difference for longer chains of conditionals. It is also useful in loops, for example
int ch;
while ((ch = reader.Read()) != -1) {
// Do something with ch
}