Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i get the generic type of an object?

Tags:

c#

list

generics

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

like image 256
dubi Avatar asked Jan 20 '26 01:01

dubi


2 Answers

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);
like image 59
Kobi Avatar answered Jan 21 '26 14:01

Kobi


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.

like image 43
Sky Sanders Avatar answered Jan 21 '26 15:01

Sky Sanders



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!