Search code examples
c#reflectionactivator

Create instance with Activator


Assume we have some classes

class Class1{ }
class Class2{ }
class Class3{ }

and I have a Type variable

Type t = /*some type unknown at compile-time*/;

variable t is Class1 or Class2 or Class3. I want to create an instance of that class. As I know I can use the following statement:

object instance = Activator.CreateInstance(t);

But I receive an object. And the question is: how do I cast this object to type that is in variable t. Or maby someone can suggest a workaround. Thanks


Solution

  • Unless there is some common base-class or interface that all 3 share, you can't - all you can call it is "object". Consider having them all implement an interface, and cast to that.