Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get General Type of class<T> use Type of Type

Tags:

c#

I have a General Class named MyGeneralClass:

public MyGeneralClass<T> {

public List<T> Data {get; set;}

}

also I have another method that I need to use it:

public void GetData(Type type) {



}

I Use GetDatalike this:

GetData(typeof(MyGeneralClass<person>));

So my question is that how can I find type of T, (in this example person) in GetData method, I can't change the parameters of GetData but I can change implementation of that. Does any one have any idea about this?

like image 414
Saeid Avatar asked Jan 26 '26 12:01

Saeid


2 Answers

Via reflection:

if(type.IsGenericType &&
     type.GetGenericTypeDefinition() == typeof(MyGeneralClass<>))
{
   Type firstArg = type.GetGenericArguments()[0];
}
like image 113
Marc Gravell Avatar answered Jan 29 '26 02:01

Marc Gravell


You can use the GetGenericArguments method:

Type t = type.GetGenericArguments()[0];
like image 21
Guffa Avatar answered Jan 29 '26 02:01

Guffa



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!