Forums

Working with type objects at run-time

General discussion about Cobra. Releases and general news will also be posted here.
Feel free to ask questions or just say "Hello".

Working with type objects at run-time

Postby Charles » Sat Mar 29, 2008 12:07 pm

In .NET/Mono, types are present at run-time as instances of System.Type. You can access them directly like so:
t = MyClass
# which is equivalent to saying:
t as System.Type = MyClass
# or
t as Type = MyClass

This works for classes, interfaces, structs, enums and delegates/signatures.

In C#, people are expected to wrap types with "typeof(MyClass)" in these situations, but Cobra does not require it. However, you may still need to express that you need the type instance in which case you can use "getType" directly on the class like so:
for method in MyClass.getType.getMethods
print method
# or
t = MyClass
for method in t.getMethods
print method

Or, if you want the type of the object at run-time, you can use .getType on it:
def foo(x)
print x.getType

If you are checking the type for inheritance purposes, though, use the "inherits" operator. When used with an if-statement, you can use the object as if it is that type inside the body of the "if":
if vehicle inherits Car
print vehicle.milesPerGallon

See also the MSDN docs on System.Type

If you'd like to explore all the type objects in an assembly (.exe or .dll), see the Assembly class. You can see some example usage of assemblies in CobraLang.cobra which ships with Cobra (even if you're not using the source version). Just search for "assembl".
Charles
 
Posts: 2515
Location: Los Angeles, CA

Return to Discussion

Who is online

Users browsing this forum: No registered users and 38 guests