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)