0

Is there a way in C# to get the definition of a type from a string? I'd like to use it as a generic type parameter.

This is what i'd like to achieve in the end.

    string classname = "Class1";
    GenericClass<Class1> gc = new GenericClass<Class1>();
    gc.Method();

is there any possible way?

2
  • You mean creating a type on the fly? Commented Dec 5, 2013 at 12:45
  • You can create the instance, but from that point onward you will be forced to work with it using reflection (unless there is additional information you have not given) -- i.e. you cannot then write gc.Method(). This will be slow and the compiler will not be able to catch any errors you make. Are you sure that's what you need to do? Commented Dec 5, 2013 at 12:50

1 Answer 1

3

Yes, you can use reflection to do it and sometimes it cannot be too safe, try something like this article sample.

Type d1 = typeof(GenericClass<>);

Type[] typeArgs = { Type.GetType("Class1") };

Type makeme = d1.MakeGenericType(typeArgs);

object o = Activator.CreateInstance(makeme);

But you will not get all intellisense from visual studio.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.