37

I have a C# method that I need to call from a piece of Ruby that requires a System.Type argument. Is there a Ruby equivalent to typeof in C#? The call will look something like this in C# ...

var CustomClasInstance = Container.GetInstance(typeof(ICustomClass))

4 Answers 4

63

Either Object.class or Object.type should do what you need.

Also, the two methods Object.is_a? and Object.instance_of? can be used. However, they are not 100% identical. The statement obj.instance_of?(myClass) will return true only if object obj was created as an object of type myClass. Using obj.is_a?(myClass) will return true if the object obj is of class myClass, is of a class that has inherited from myClass, or has the module myClass included in it.

For example:

x = 1
x.class                   => Fixnum
x.instance_of? Integer    => false
x.instance_of? Numeric    => false
x.instance_of? Fixnum     => true
x.is_a? Integer           => true
x.is_a? Numeric           => true
x.is_a? Fixnum            => true

Since your C# method requires a very specific data type, I would recommend using Object.instance_of?.

41

In addition to checking Object#class (the instance method class on the Object aka Base class), you could

s.is_a? Thing

this will check to see if s has Thing anywhere in its ancestry.

7

For a reference on how to identify variable types in Ruby, see http://www.techotopia.com/index.php/Understanding_Ruby_Variables#Identifying_a_Ruby_Variable_Type

If you have variable named s, you can retrieve the type of it by invoking

s.class
1
  • 2
    It looks like s.Class is more like CustomClassInstance.GetType() and not really like typeof(CustomClass) ... am I mistaken?
    – Chris
    Feb 3, 2010 at 14:02
0
ICustomClass.to_clr_type

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.