Bad Code: _dog as Animal

I recently came across a post which gave an example of poorly written code, which the person used in job interviews. His strategy was sound, as he didn’t expect people not to be stumped by the code but rather wanted to see how people would act when they came across such code.

The code was the following:

// The Dog class is inherited from the Animal class
for (Dog _dog = _animal as Dog; _dog != null; _dog = null)
{
// Other code runs
}

He goes as far as giving an example of how he would rewrite the above code to make it easier to read, which was as follows:

Dog _dog = _animal as Dog;

if (_dog != null) {
// more code
}

While I imagine, the code would continue to work as intended, I couldn’t help but notice that he hadn’t rewrote the code to exactly match what the original code did. He could of done multiple things to correct this and wouldn’t of taken much more time.

Dog _dog = _animal as Dog;

if (_dog != null) {
// more code
_dog = null;
}

Another way to do this as well (if the variable _dog isn’t used further on and to more accurately mimic the original code) would be to wrap the code in parenthesis. Which would then clean up _dog after it leaves the parenthesis it’s contained within, which I think would be the reason for writing the code the original way.

{

Dog _dog = _animal as Dog;
if (_dog != null) {
// more code
}

}