I wonder if it is possible to add a subclass in runtime while using C#.
I like to set a type on the main class and if possible having some code select the correct inheritance based on this information, is a thing like that possible to achieve?.
Here is a small example in the direction in what I like to do?.
Regards, Magnus
using System;
namespace ClassTest
{
class Animal
{
public string type = "[Not set!]"; // use the correct class based on thi value.
public virtual string WhatDoesTheAnimalSay()
{
return "[no animal selected!]";
}
}
class Cat : Animal
{
public override string WhatDoesTheAnimalSay()
{
return "Meow!";
}
}
class Dog : Animal
{
public override string WhatDoesTheAnimalSay()
{
return "Woof!";
}
}
class Program
{
static void Main(string[] args)
{
// Cat cat = new Cat();
// Console.WriteLine("The Cat says: " + cat.WhatDoesTheAnimalSay());
// Dog dog = new Dog();
// Console.WriteLine("The Dog says: " + dog.WhatDoesTheAnimalSay());
Animal unknown = new Animal();
unknown.type = "Dog";
Console.WriteLine("The " + unknown.type + " says: " + unknown.WhatDoesTheAnimalSay());
Console.ReadKey();
}
}
}