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?
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!
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
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.
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.
(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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With