title: C# Randomize inherited class without hardcoding
body: <p>What I want to achieve is to by either name of derived class or enum name generate a random derived class. While my code works in this case, it will require a lot of hardcoding if i decide to expand on it and to me it seems like a bad solution.</p>
  <p>Here is my example code: (the UnitTypes variable includes all derived class names dynamically, so i feel like it may be useful - but I could figure out how to.)</p>
  <pre><code>public void Run()
          {
  
              var UnitTypes = Assembly.GetExecutingAssembly().GetTypes().Where(t =&gt; t.BaseType == typeof(Unit));
              Unit NewMonster = new Unit(); //&lt;---
  
          konny: //for testing things out.
  
              int RandomType = new Random().Next(0, UnitTypes.Count());
  
              switch (RandomType)
              {
                  case 0:
                      NewMonster = new Dingo();
                      break;
                  case 1:
                      NewMonster = new Buffalo();
                      break;
                  case 2:
                      NewMonster = new Dog();
                      break;
              }
              Console.WriteLine($&quot;A wild {NewMonster.Name} appears&quot;);
              NewMonster.Attack();
              Console.ReadLine();
  
              goto konny;            
          }
  </code></pre>
  <p>And the Baseclass + 1 derived for sake of example.</p>
  <pre><code>    public class Unit
      {
          public Enemies Name { get; set; }
  
          public enum Enemies
          {
              Dingo, Buffalo, Dog
          }
  
          public virtual void Attack()
          {
              //nothing to see here
          }
     
      }
  
      class Dingo : Unit
      {
  
          public Dingo()
          {
              Name = Enemies.Dingo;
          }
  
          public override void Attack()
          {
              Console.WriteLine($&quot;{Name}  gnaws at your brain&quot;);
          }
  
      }
  </code></pre>