3

I have a class:

public class MyClass<T>

I have a config file that I am reading that has, say, Guid for the type T.

How do I do this, except using the string from the config file instead of the actual type (instead of hard-coding Guid)?

MyClass<Guid> = new MyClass<Guid>();
Morvader
  • 2,317
  • 3
  • 31
  • 44
mikeb
  • 10,578
  • 7
  • 62
  • 120
  • What you mean by `instead of hard-coding Guid`? – sll Oct 31 '11 at 15:54
  • This makes no sense. Why do you want to do this? If the type argument is dynamic, then there's no point in using generics which facilitate parameterized *static* typing. – Kirk Woll Oct 31 '11 at 15:55
  • You are in a weird situation when you have to interact directly with generated types. (I assume the type whose name is a GUID is generated.) – Dan Davies Brackett Oct 31 '11 at 15:56

1 Answers1

2

You need the fully qualified type name:

var typeArgument = Type.GetType("System.Guid");

Then you can use reflection to get the parameterized type:

var genericType = typeof(MyClass<>).MakeGenericType(typeArgument);

Which you can then instantiate via:

var instance = Activator.CreateInstance(genericType);

But I'm not sure why you would want to do this or why it would be useful in your scenario. Since using this technique, you'll never be able to interact with MyClass<T> where T is defined as something you're specifying at compile-time, you lose most of the advantages of using generics in the first place.

Kirk Woll
  • 76,112
  • 22
  • 180
  • 195