Compartilhar via


Teaching Casting

I love a good analogy. Actually I even like so-so analogies. But this one about casting variables from Rob Miles is a particularly good one I think. I can see saying “and now playing the role of an integer is 3.14159” What was that you are asking? Well those of you who haven’t read Rob’s post are asking anyway. So here is the deal.

In programming sometimes we need to cast a variable of one type into the role of acting like a variable of another type. For example we want a pair of integers to act like real numbers so that we can get an answer with a fractional part. Sometimes it is hard for students to get the picture of what is happening though. So I like Rob’s analogy of “You can think of casting as making a movie. You take an actor (Christian Bale) and cast him as a character (Batman). For the duration of the film the character will behave in terms of the role they have been cast into.

I think the original meaning relates to foundry work though. Melting something and pouring into a mold. But on the other hand casting in the role sense makes it easier to see casting the same variable multiple ways for multiple uses. Besides even the high school I attended doesn’t teach casting in metal anymore – though foundry was a required class when I was a student. Students do understand casting for roles in plays, movies and TV shows though.