imgen
imgen

Reputation: 3133

How to get typeof(List<>) from typeof(List<T>) by removing generic argument

I have typeof(List<T>) as a Type object, but I need the typeof(List<>) from which I can use MakeGenericType() to retrieve a type object for List, is it possible?

Update: Guys, thx. This seems a trivial question. But anyway, I upvoted everyone and accepted the first answer.

Upvotes: 3

Views: 12457

Answers (4)

SWeko
SWeko

Reputation: 30942

If I undestand your problem correctly, you have a generic type (List<int>) and another type (lets say long) and you want to make a List<long>. That can be done like this:

Type startType = listInt.GetType();   // List<int>
Type genericType = startType.GetGenericTypeDefinition()  //List<T>
Type targetType = genericType.MakeGenericType(secondType) // List<long>

However, if the types you are working with are indeed lists, it might be clearer if you actually used:

Type targetType = typeof(List<>).MakeGenericType(secondType) // List<long>

Upvotes: 5

Douglas
Douglas

Reputation: 54927

I assume you mean to achieve something like the below?

var list = new List<int>();
Type intListType = list.GetType();
Type genericListType = intListType.GetGenericTypeDefinition();
Type objectListType = genericListType.MakeGenericType(typeof(object));

Upvotes: 1

Venemo
Venemo

Reputation: 19107

The answer is Type.GetGenericTypeDefinition:
http://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition.aspx

Example:

var t = typeof(List<string>);
var t2 = t.GetGenericTypeDefinition();

And then could do this:

var t = typeof(List<>);
var t2 = t.MakeGenericType(typeof(string));

Upvotes: 0

Nick Hill
Nick Hill

Reputation: 4927

You can use Type.GetGenericTypeDefinition.

Upvotes: 3

Related Questions