1

Is it possible to create an instance of a class of type T depending on the type of a runtime variable?

For example:

var myType = myVariable.GetType();
var myTestClass = new TestClass<myType>(); 

This will not compile but hopefully shows what I'm trying to achieve.

Is there a way?

EDIT

Say the class is like this:

public class TestClass<T>
{     
    public string StringValue
    {
        get
        {
            return this.TypeValue == null ? string.Empty : this.TypeValue.ToString();
        }   
    }

    public T TypeValue { get; set; }  
}

If I did something like:

var test1 = TestClass((dynamic)x); // x is an int

I would be able to set like test1.TypedValue = 10

If I did something like:

var test2 = TestClass((dynamic)y); // y is a bool

I would be able to set like test2.TypedValue = true

At the moment I get an error stating

cannot implicitly convert type int to TestClass (or bool to TesClass)

davy
  • 4,474
  • 10
  • 48
  • 71

1 Answers1

6

Yes, but you have to use reflection:

object myTestClass = Activator.CreateInstance(
    typeof(TestClass<>).MakeGenericType(myType));

If your TestClass<T> implements a non-generic interface or has a non-generic base-class, it will be more usable:

ITestClass myTestClass = (ITestClass) Activator.CreateInstance(
    typeof(TestClass<>).MakeGenericType(myType));

You can also cheat with dynamic (which does the reflection for you, and caches the optimized strategy for performance, etc):

Evil((dynamic)myVariable);
...
void Evil<T>(T val)
{
    var myTestClass = new TestClass<T>();
    //...
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900