Reputation: 20004
I don't think that this could be done in C#, but posting this just to make sure. Here's my problem. I would like to do something like this in C#:
var x = 10;
var l = new List<typeof(x)>();
or
var x = 10;
var t = typeof(x);
var l = new List<t>();
But of course this doesn't work. Although this shouldn't be a problem as the type t is resolved at compile time. I understand that this can be solved with reflection, but as types are known at compile time using reflection would be overkill.
Upvotes: 14
Views: 5054
Reputation: 99734
You can't do it exactly how you are asking, but with a little reflection you can accomplish the same thing
Type genericType = typeof(List<>);
Type[] type = new Type[] { typeof(int) };
Type instanceType = genericType.MakeGenericType(type);
object instance = Activator.CreateInstance(instanceType );
var l = (List<int>)instance;
Upvotes: 2
Reputation: 20076
public static List<T> CreateCompatibleList<T> (T t)
{
return new List<T> () ;
}
var x = 10 ;
var l = CreateCompatibleList (x) ;
Upvotes: 41
Reputation: 415820
You're trying to get .Net to set a generic type using a run-time operator. As you know, that won't work. Generics types must be set at compile time.
Upvotes: 6
Reputation: 25523
Defining generics is done like this in C#:
var someList = new List<int>();
You can not define generics like this:
var x = 1;
var someType = typeof(x);
var someList = new List<someType>();
because you're specifying the type at run time in this case, not compile time. C# doesn't support that.
Upvotes: 3