Try Cast?

BlitzMax Forums/BlitzMax Beginners Area/Try Cast?

BLaBZ(Posted 2012) [#1]
I want to "Try" cast an Object type to determine what type it is?

How would I go about this?


Example: I have a Object that could be a truck, car, or sportscar,

I want to "try cast" to figure out which one it is.


ziggy(Posted 2012) [#2]
Class name is the type cast operator
Local MyCar:TCar = TCar(UnknownObject)

If MyCar is Null, UnknownObject was not a TCar, otherwise, it gets casted to TCar and assigned to the MyCar local pointer.


BLaBZ(Posted 2012) [#3]
I keep getting the message unable to convert from 'car' to <unknown>

and it won't compile.

Does the object have to be somewhere in the inheritance chain?


ziggy(Posted 2012) [#4]
Can you paste some source code?


BLaBZ(Posted 2012) [#5]

SuperStrict
Type truck
	Field Name:String
End Type


Type car
	Field Name:String
End Type

Type sportscar Extends car
	Field Name:String
End Type

Local aCar:car = New car

Local aClass:truck = truck(aCar)


If aClass = Null
	Print "null"
Else
	Print "not null"
EndIf 




Jesse(Posted 2012) [#6]
That's a weakness of the language the object has to be related or of type "Object" to do the test.
this work:
SuperStrict
Type truck
	Field Name:String
End Type


Type car
	Field Name:String
End Type

Type sportscar Extends car
	Field Name:String
End Type

Local aCar:car = New car

If isTruck(aCar)
	Print "not null"
Else
	Print "null"
EndIf 


Function isTruck:Int(obj:Object)
	Return truck(obj) <> Null 
End Function


or this:
SuperStrict

Type vehicle
	Field name:String
End Type

Type truck Extends vehicle
End Type


Type car Extends vehicle
End Type

Type sportscar Extends vehicle
End Type

Local aCar:vehicle = New car

Local aClass:truck = truck(aCar)


If aClass = Null
	Print "null"
Else
	Print "not null"
EndIf 


in reality if you are encapsulating an object properly you should not have to do that test at all.

Last edited 2012