Skip to main content
1 of 2

Imagine that you are a manufacturer of flanges. You have a great deal of flanges in your possession, more than you can reasonably store in your own garage, so you've purchased a warehouse in which to store your inventory.

One day you receive a large order that must be fulfilled with all haste, so you go to your warehouse manager, Carl the Compiler (whose epithet is a matter of some mystery), and ask him to assist you in doing so.

"What kind of flanges do you need?" Carl asks you.

"It doesn't matter," you say, "the customer just wants 100 flanges."

It just so happens that Carl is sitting on top of a large pile of boxes, each of which is clearly marked as containing a frobnosticating flange. Carl points out that it is trivially provable that all frobnosticating flanges are flanges, and orders that the entire mountain of boxes be immediately shipped to the customer.

This is upcasting.

The next day you receive another order, but this time the client is more specific: rather than requiring any kind of flange, he needs 100 defenestrating flanges. You return to Carl to ask for his assistance.

Unfortunately, it seems that the marketing department has decided to relabel all of the packages in the warehouse. Rather than each box being clearly labeled, they now simply read 'FLANGE' in a tasteful humanist font.

You inform Carl of the new order for defenestrating flanges.

"That could be a bit of a problem," he says. "Ever since marketing relabeled all of the boxes, I have no idea what kind of flange is inside any of them."

You pick one of the boxes at random and hand it to Carl and ask, 'box is DefenestratingFlange?'

He opens the box and pulls out the frobnosticating flange inside. 'false,' he replies.

Fortunately, you suddenly remember that you had specifically set aside 100 defenestrating flanges earlier that week, hiding them away in a unused room so that nobody else would take them. You go to the room and, lo and behold, the boxes are still there, though they—like all the rest—have been 'updated' with the new labels.

You carry these boxes out to Carl and tell him to ship them to the customer with all haste.

"But I can't verify that these are defenestrating flanges," he objects.

"That's fine," you tell him, "I have special knowledge that they are. I'm the boss, and you can trust me to know what I'm talking about, so just do it."

Carl accepts this and does as you ask.

This is downcasting.

You then realize that you've misplaced one of the boxes, leaving you one flange short of the 100 that were ordered. To rectify this, you retrieve a random box from the warehouse—not bothering to check what's actually inside—and throw it in with the rest.

'InvalidCastException,' Carl complains.

You open the box. There's a frobnosticating flange inside.

Well, nobody's right all the time.