title: Change generic type from within the class
body: <p>I have this class to generate random objects:</p>
  
  <pre><code>public class Generator&lt;T&gt;
  {
      private Random rnd = new Random();
      private List&lt;Type&gt; types = new List&lt;Type&gt;();
  
      public Generator()
      {
          //can't a generic type constraint that says "implements any interface" so I use this ugly thing...
          if (!typeof(T).IsInterface)
              throw new Exception("Generator needs to be instanciated with an interface generic parameter");
  
          types = Assembly.GetExecutingAssembly().GetTypes().Where(x =&gt; x.GetInterfaces().Contains(typeof(T))).ToList();
      }
  
      public T GetRandomObject()
      {
          int index = rnd.Next(types.Count);
          return (T)Activator.CreateInstance(types[index]);
  
      }
  
      public void SetNewGeneric&lt;N&gt;()
      {
          T = N; //this doesn't work...
          types = Assembly.GetExecutingAssembly().GetTypes().Where(x =&gt; x.GetInterfaces().Contains(typeof(T))).ToList();
      }
  
  }
  </code></pre>
  
  <p>I use it like so:</p>
  
  <pre><code>Generator&lt;IEnemy&gt; generator = new Generator&lt;IEnemy&gt;();
  var randomEnemy = generator.GetRandomObject(); //create and return randomly, any object that implements IEnemy...
  </code></pre>
  
  <p>My question is, is there any way to change the type of <code>T</code> at runtime so I can do something like</p>
  
  <pre><code>generator.SetGeneric&lt;IWeapon&gt;();
  var weapon = generator.GetRandomObject();
  </code></pre>
  
  <p>Any other ways I could do this if I'm taking the wrong path ?</p>
  
  <p>Thanks.</p>