The most creative abuse of C#…

My coworker JSR has, by presenting on the topic, staked out the position of Lead C# Expert where I work.  So it is with no small amount of relish that I enjoy finding code samples that either stump him or make him want to gag.  In a blog post I found what is perhaps the most “creative abuse” of C# I’ve ever seen.  The scenario is this: I have a variable of the type Animal, and among it’s various subclasses in the program is the type Dog and I want to run some logic on an instance of animal, but only if it’s a Dog… and I only want to run it once. Here’s one possibility:

for (Dog dog = animal as Dog; dog != null; dog = null) {
//put your “only if it’s a dog” code here
}

Admittedly, this is a hack, and an ugly one at that… but it works perfectly fine. It’s also a case of code that is so obtuse as to be incomprehensible to junior developers, and probably more than a few seasoned ones as well. The more sane way to accomplish the same in only one more line of code is this:

Dog dog = animal as Dog;
if (dog != null) {
//put your “only if it’s a dog” code here
}

But hey, if saving a single line of code is worth making your logic unreadable the feel free to use the for() construct above. More on this manner of code abuse at: http://stackoverflow.com/a/7113387.