Best way to detect class of variable
Monkey Forums/Monkey Programming/Best way to detect class of variable
| ||
Consider the following snippet of code...Class base End Class Class foo Extends base End Class Class bar Extends base Field sText:String="working as expected" End Class Function Main() 'Working as expected Local a:base = New bar Print bar(a).sText 'Causes Error at runtime (correct) Local b:base = New foo Print bar(b).sText End Function If you run the above code you will see it print... working as expected Monkey Runtime Error : Null object access This is correct and expected. My question is, what is good way of detecting if variable 'b' is indeed of class bar?. So that I know not to run 'Print bar(b).sText'. |
| ||
One solution I have is this...Class base Method ClassType:Int() Abstract Const iTYPE_FOO:Int = 1 Const iTYPE_BAR:Int = 2 End Class Class foo Extends base Method ClassType:Int() Return base.iTYPE_FOO End Method End Class Class bar Extends base Method ClassType:Int() Return base.iTYPE_BAR End Method Field sText:String="working as expected" End Class Function Main() 'Working as expected Local a:base = New bar Print bar(a).sText 'Causes Error at runtime (correct) Local b:base = New foo If b.ClassType() = base.iTYPE_BAR Print bar(b).sText Endif End Function Now this is not ideal as it means implementing a method that I would rather not have in each of the extended classes. Also means looking after a list of constants as well. Feature request: If we could abstract Constants then we would be able to do the above much simpler!. |
| ||
Figured it out...Class base End Class Class foo Extends base End Class Class bar Extends base Field sText:String="working as expected" End Class Function Main() 'Working as expected Local a:base = New bar Print bar(a).sText 'Causes Error at runtime (correct) Local b:base = New foo If bar(b) <> null Print bar(b).sText Endif End Function And that is the solution I was looking for!. |