C# - How to access a generic typed property

Posted on Thursday, August 15, 2013 by Nicki

My challenge for today was to get the value of generic typed properties from a generic type. Here is the code that worked.

pendingRequest is a generic-typed instance of RequestResponseAsyncResult where the Request and Response properties are generic.

First we have to get the generic type definition:

Type requestType = pendingRequest.GetType().GetGenericTypeDefinition();
Next we get the generic type arguments:
Type[] typeArgs = requestType.GetGenericArguments();
Then we create a generic base type from our generic type:
Type genericType = typeof(RequestResponseAsyncResult<,>);
The next step is to created a generic type according to the type arguments:
Type constructed = genericType.MakeGenericType(typeArgs);
Now we are able to get the property information:
PropertyInfo pireq = pendingRequest.GetType().GetProperty("Request");
PropertyInfo piresp = pendingRequest.GetType().GetProperty("Response");
Finally we can get our properties using reflection:
object request = pireq.GetValue(pendingRequest, null);
object response = piresp.GetValue(pendingRequest, null);



0 Responses to "C# - How to access a generic typed property":