Switching a type check
January 25, 2009 – 6:23 amA colleague was recently trying to determine a way to use a Switch for the type of Display Object he was feeding, that is, to have a case for a Sprite, another for a Bitmap, etc.
In if…else language it would be easy, using the is operator:
if (obj is Bitmap) {
doBitmap();
} else if (obj is Sprite) {
doSprite();
...etc
…but it’s annoying that the nature of “is” doesn’t lend itself to switches, and it seems that other languages have the same stumbling block.
It would obviously be best to make sure that everything you are feeding in is your own class with a method doThing(), as this would make things much neater and cleaner, but that’s not always possible, including in the case I was being shown.
Instead I was toying with the following solution:
var bmp : Bitmap = new Bitmap();
var spr : Sprite = new Sprite();
var obj : Object = {};
function getType(obj : *) : void {
switch(true) {
case obj is Bitmap:
trace('Bitmap');
break;
case obj is Sprite:
trace('Sprite');
break;
default:
trace('Neither');
break;
}
}
getType(bmp);
getType(spr);
getType(obj);
As with any switch, you need to be careful with the order in which you have the statements, eg you’d have MovieClip before Sprite in the cases, otherwise it would get trapped too early.
Interestingly, this solution seems to work in VB.NET but not C#, as C# only deals with Strings & Ints, while VB takes any primitive.

2 Responses to “Switching a type check”
A quick performance test I ran showed that using if..else for type checking is faster than using switch(true).
By Nicolas on Apr 1, 2009
Yep, I don’t doubt you for a second!
This is more for readability and “cleanness” of code – unless there are going to be hundreds/thousands of these checks then I would view the time saving as negligible, but everyone has their own style.
By admin on Apr 14, 2009