T
Timothy V
Hi,
I have a problem. How do i create an instance of an unknown derived class?
I'll explain more with the following code.
abstract class Animal {}
sealed class Dog {}
sealed class Cat {}
Animal GetAnimal(string name)
{
if (name = "a")
return new Dog();
else
return new Cat();
}
static void Main()
{
Animal a = GetAnimal("a");
a.GetType() // This will be 'Dog'
}
From this code, I end up with a Dog instance inside Animal. Because it could
be a Cat, how do I dynamically cast it to the type it actually is?
I hope that makes sense because i'm stuck :-(
Thank you in advance,
Tim.
I have a problem. How do i create an instance of an unknown derived class?
I'll explain more with the following code.
abstract class Animal {}
sealed class Dog {}
sealed class Cat {}
Animal GetAnimal(string name)
{
if (name = "a")
return new Dog();
else
return new Cat();
}
static void Main()
{
Animal a = GetAnimal("a");
a.GetType() // This will be 'Dog'
}
From this code, I end up with a Dog instance inside Animal. Because it could
be a Cat, how do I dynamically cast it to the type it actually is?
I hope that makes sense because i'm stuck :-(
Thank you in advance,
Tim.