Let say I have a generic member in a class or method, so:
public class Foo<T>
{
public List<T> Bar { get; set; }
public void Baz()
{
// get type of T
}
}
When I instantiate the class, the T
becomes MyTypeObject1
, so the class has a generic list property: List<MyTypeObject1>
. The same applies to a generic method in a non-generic class:
public class Foo
{
public void Bar<T>()
{
var baz = new List<T>();
// get type of T
}
}
I would like to know, what type of objects the list of my class contains. So the list property called Bar
or the local variable baz
, contains what type of T
?
I cannot do Bar[0].GetType()
, because the list might contain zero elements. How can I do it?
You can use this one for rerun type of generic list.
That's work for me. Where myList is some unknowed kind of list.
Using 3dGrabber's solution:
This is how i did it
Then call it like this
OR
You can get the type of "T" from any collection type that implements IEnumerable<T> with the following:
Note that it doesn't support collection types that implement IEnumerable<T> twice, e.g.
I suppose you could return an array of types if you needed to support this...
Also, you might also want to cache the result per collection type if you're doing this a lot (e.g. in a loop).