89

Is it possible to achieve the following code? I know it doesn't work, but I'm wondering if there is a workaround?

Type k = typeof(double);
List<k> lst = new List<k>();
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Chris
  • 1,089
  • 2
  • 10
  • 9
  • Bit confused by your comment "this can be accomplished in C# 4.0." It can't, at least not in the way you show it. C# 4 still requires generic type parameters to be specified at compile time; you still can't pass a Type variable as a generic type parameter. – itowlson Jan 16 '10 at 21:16
  • 1
    Please phrase things as a question when it is a question. The code as specified can not be accomplished with C# 4.0. – Lasse V. Karlsen Jan 16 '10 at 21:17
  • 1
    Similar question: http://stackoverflow.com/questions/687363/how-do-i-create-a-generic-class-from-a-string-in-c – Zach Johnson Jan 16 '10 at 21:17
  • Sorry about the C# 4.0 thing. I meant that the answer could use concepts in C# 4.0, not necessarily that the code would work in C# 4.0. Thanks for the edit DrJokepu. – Chris Jan 16 '10 at 21:26
  • Doesn't generics already do this!?!? – bbqchickenrobot Aug 29 '11 at 01:25
  • 12
    I think this question is stated perfectly -- just the right amount of detail! – RunHolt Jan 11 '13 at 21:42
  • possible duplicate of [Dynamically Create a generic type for template](http://stackoverflow.com/questions/67370/dynamically-create-a-generic-type-for-template) – nawfal Jan 17 '14 at 14:37

2 Answers2

121

Yes, there is:

var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);
David M
  • 71,481
  • 13
  • 158
  • 186
  • I think this is what I want. Let me double check and I'll mark yours as the answer momentarily. – Chris Jan 16 '10 at 21:14
  • 4
    I think the main problem here is that you don't describe what you want to *us*. You show us a failed attempt at *something* and then asks how to accomplish what *you want*. If you want answers, and not guesses, you should describe what you need to do, instead of how you attempted to do it. – Lasse V. Karlsen Jan 16 '10 at 21:18
  • I basically want to create a List<> where the type is specified as a Type variable. – Chris Jan 16 '10 at 21:20
  • 3
    Thanks David M, your code does exactly what I needed. Sorry to those who were unable to answer because I didn't provide an adequate question. – Chris Jan 16 '10 at 21:25
3

A cleaner way might be to use a generic method. Do something like this:

static void AddType<T>()
    where T : DataObject
{
    Indexes.Add(typeof(T), new Dictionary<int, T>());
}
Bryan Legend
  • 6,790
  • 1
  • 59
  • 60
  • I'm not sure what you mean by "Indexes", is that a variable declared elsewhere? – jrh Dec 13 '19 at 14:06