by Matt
1. January 2007 17:33
You've got to love Jeremy D. Miller. And not only because Jeremy D. Miller is a name my dad would approve of ("You have a middle name for a reason, son"). No, it's mainly because he continually writes dead good stuff.
Take this post on downcasting.
(Downcasting being the act of casting an object reference from a base class to a derived class.)
Just before the Christmas break, I had to send out an email to my team, berating them for doing just this.
Jeremy's a lot more polite about it that I want to be. It's quite simple.
If you're downcasting from a base class to a derived class in your code, your spidey sense should be tingling. Go and talk to someone you trust.
If you actually have the gall to cast an abstract interface to a concrete class, then your spidey sense should be smacking you round the back of the head with a length of 2 x 4. You're almost certainly doing something wrong.
And yes, there are exceptions. There are always exceptions. Hopefully, it's design flaws in 3rd party software (including the .net framework itself) that you can't work around. Or if you're lucky, using object as a generic type.
Just don't do it in your own code please.
Now go read Jeremy D. Miller's post (might as well subscribe while you're there). It's a good one, and has some good links in it. Especially the Tell, Don't Ask link - a concept (like so many others) that work great on the simple examples in the literature, but are not quite so obvious on Real Life Code.
e2b65718-0ced-4cf6-b247-14af805f214a|0|.0
Tags: