Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the type of T from a member of a generic class or method

Tags:

c#

.net

generics

Let's say I have a generic member in a class or method, like 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 what type of T does the list property called Bar or the local variable baz contain?

I cannot do Bar[0].GetType(), because the list might contain zero elements. How can I do it?

like image 562
Patrick Desjardins Avatar asked Feb 17 '09 15:02

Patrick Desjardins


People also ask

How do you find a parameter type?

You can access the type of a specific parameter by using square brackets, in the same way you would access an array element at index. Here is an example of how you would use the Parameters utility type for 2 functions that take the same object as a parameter. Copied!

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

What is T in a method C#?

In C#, the “T” parameter is often used to define functions that take any kind of type. They're used to write generic classes and methods that can work with any kind of data, while still maintaining strict type safety.


2 Answers

If I understand correctly, your list has the same type parameter as the container class itself. If this is the case, then:

Type typeParameterType = typeof(T); 

If you are in the lucky situation of having object as a type parameter, see Marc's answer.

like image 122
Tamas Czinege Avatar answered Sep 30 '22 01:09

Tamas Czinege


(note: I'm assuming that all you know is object or IList or similar, and that the list could be any type at runtime)

If you know it is a List<T>, then:

Type type = abc.GetType().GetGenericArguments()[0]; 

Another option is to look at the indexer:

Type type = abc.GetType().GetProperty("Item").PropertyType; 

Using new TypeInfo:

using System.Reflection; // ... var type = abc.GetType().GetTypeInfo().GenericTypeArguments[0]; 
like image 20
Marc Gravell Avatar answered Sep 30 '22 02:09

Marc Gravell