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)

0

1 Answer 1

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>();
    //...
}
Sign up to request clarification or add additional context in comments.

5 Comments

+1 for cheating .. evilishly
@quetzalcoatl actually, I did screw up the call; fixed in edit
@davy if myVariable is int, then what is myProp ? what declares myProp? because it clearly isn't the int...
@davy no, not really; an actual example would really help
@Marc - I'v edited the question. Happy to clarify further if required.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.