Check if two objects are of the same type?

BlitzMax Forums/BlitzMax Programming/Check if two objects are of the same type?

Azathoth(Posted 2012) [#1]
Is there a way (without reflection) to check if two objects are of the same type?

For instance this function will swap two objects, the only rule is as long as they are objects it will swap them even if they are incompatible (eg. a string and an array), breaking the casting system.

Function swap(o1:Object Var, o2:Object Var)
	Local t:Object
	
	t=o1
	o1=o2
	o2=t
EndFunction



Htbaa(Posted 2012) [#2]
Have your tried using the Compare() method?


Jesse(Posted 2012) [#3]
you can probably do it with reflection. although I have never tried it so I don't know for sure.

What I am wondering how and why would you get in to the situation of passing a string and an array to swap them. I am pretty sure that if you are programming the comparison you would know what is being sent to the swap function.

I have gotten to situations of having to find out if the two objects are compatible but only after passing objects of same base type and using the base type as the parameter but that also was until I started learning proper polymorphic and encapsulation usage.

Last edited 2012


H&K(Posted 2012) [#4]
If these are user created objects (ie you wrote them) then just put a global field in each one with a type name.

This adds only the single string overhead to the whole type, then you just compare the two names

Last edited 2012


matibee(Posted 2012) [#5]
Check out niliums code here...

http://www.blitzbasic.com/Community/posts.php?topic=97931


Azathoth(Posted 2012) [#6]
The objects are items in a priority queue so the idea is the swap function shouldn't make any assumptions besides both being the same type.

I'm using something like niliums already.


TomToad(Posted 2012) [#7]
If you don't want to use reflection, you could use abstract functions instead.
[bbcode]Type TBase
Function Class:String() Abstract
End Type

Type T1000 Extends TBase
Function Class:String()
Return "T1000"
End Function
End Type

Type T2000 Extends TBase
Function Class:String()
Return "T2000"
End Function
End Type

Function Compare:String(TB1:TBase, TB2:TBase)
If TB1.Class() = TB2.Class() Then Return "Equal"
Return "Not equal"
End Function

Local t1:T1000 = New T1000
Local t2:T2000 = New T2000
Local t3:T1000 = New T1000

Print Compare(t1,t2)
Print compare(t1,t3)
[/bbcode]

Last edited 2012