Can I get the generic object type?

this is my method: GetListItemsPainted<T>(List<T> list)

and I don't know what type this list is,

how can I create a new list that will be of the type of the passed list?

something like that:

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

      

how can I give my list to a real type so that I have all its properties, etc.?

thanks

+2


a source to share


2 answers


You don't need to create a new list, you already have one.

If you need a specific type, then restrict your generic type parameters with where

If you intend to react to a large number of arbitrary types, which I think is a bad design decision, then you will need to use a conditional with .Cast<T>()



sort of:

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.

+1


a source


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 to do this to work with generics:

Type myType = typeof(T);

      

+10


a source







All Articles