Try Cast?
BlitzMax Forums/BlitzMax Beginners Area/Try Cast?| 
 | ||
| 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. | 
| 
 | ||
| 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. | 
| 
 | ||
| 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? | 
| 
 | ||
| Can you paste some source code? | 
| 
 | ||
| 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 | 
| 
 | ||
| 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 |