tags:

views:

70

answers:

2

this is my method: GetListItemsPainted<T>(List<T> list) and i don't know what type is that list of,

how can i create new list that would have the passed list type?

something like this:

List<list.GetType()> newList = new List<list.GetType()>();

how can i cast my list to the real type so i would have all his properties etc.?

thanks

+10  A: 

You can create a list using T:

List<T> newList = new List<T>();

If you must get the type, you can use typeof. This is similar to what you asked for, but has other uses, you don't need it to make generics work:

Type myType = typeof(T);
Kobi
+1  A: 

You do not have to create a new List, you already have one.

If you require a specific type, then constrain your generic type parameters with a where constraint

If you intend to react to a wide variety of arbitrary types, which is a bad design decision in my opinion, then you will need to use a conditional with .Cast<T>()

something like:

Type myListType = list.GetType().GetGenericArguments()[0];
// or Type myListType = typeof(T); as stated by Kobi
if(myListType == typeof(SomeArbitraryType))
{
   var typedList = list.Cast<SomeArbitraryType>();
   // do something interesting with your new typed list.
}

But again, I would consider using a constraint.

Sky Sanders
thanks, it was very halpfull
dubi
@dubi - if it provided the needed guidance you should click on the checkmark.
Sky Sanders