0

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();
      }
   }
}
  • Why would you want to do that? Seems like an XY problem – adjan Oct 10 '18 at 08:16
  • @fubo, given the correct answer. If you don't know the type, then use the Activator.CreateInstance to create generic type of the instance. https://stackoverflow.com/questions/731452/create-instance-of-generic-type – Jeeva J Oct 10 '18 at 08:19

1 Answers1

2

replace

Animal unknown = new Animal();
unknown.type = "Dog";

with

Animal known = new Dog();

and forget about that string type. Each class has its type see GetType()

fubo
  • 44,811
  • 17
  • 103
  • 137
  • I suppose OP doesn´t know the exact type at **compile-time**, making `new Dog()` not feasible. – MakePeaceGreatAgain Oct 10 '18 at 08:17
  • That is correct. I only have base objects and wish to add the functions by selecting what class I need for that object. I'm writing a server emulator of a game written in C around 1996-1997 and they did use a homemade script engine. What they did is attach a script and variables to each object in the game. There is 1000's of them in the world. If this is not an easy way to solve I think about taking a tour down into Roslyn Scripting. But it looks like a dark hole to me at the moment :) – Magnus Lundberg Oct 10 '18 at 08:39