I have the following design of objects and classes. As mentioned in the comments of the method Play(Animal a), I would like to be able to test that a is effectively of type Cat<Big> and cast a accordingly so that I could access the method MethodUniqueToCats().
I am able to get Big via a.GetType().GetGenericArguments()[0]. But, somehow I am failing to make the leap on how to go from Animal to Cat<Big>. I believe that it is possible because Visual Studio is able to determine this info at runtime (checked via debug + breakpoints inside the method Play(Animal a)).
interface Animal
{
}
class Cat<T> : Animal
{
public void MethodUniqueToCats()
{
}
}
class Dog<T> : Animal
{
}
class Freetime
{
private Animal my_animal;
public void Play(Animal a)
{
my_animal = a;
Type t = a.GetType().GetGenericArguments()[0];
// I would like to test if the type of 'a' passed to this
// method is a Cat and subsequently cast it to a Cat of type 't'
// so that I can access 'MethodUniqueToCats()'.
// Line below does not work but wondering how to go about:
// if (a.GetType().IsAssignableFrom(typeof(Cat<t>))
// How to do the 'casting'
}
}
class MyProgram
{
public static void Main(string[] args)
{
Freetime f = new Freetime();
Cat<Big> c = new Cat<Big>();
f.Play(c);
}
}
Thanks in advance.