user1647697
user1647697

Reputation: 59

Get property value of instance of generic type's argument

Using reflection:

If I have an instance of type X<Y> (I don't know what Y is exactly) since X is a generic type (X<T>), how do I get the value of a property on Y?

Something like:

Type yType = currentObject.GetType().GetGenericArguments()[0];

// How do I get yInstance???
var yInstance = Convert.ChangeType(???, yType);

I need to get to:

object requiredValue = yType.GetProperty("YProperty").GetValue(yInstance, null);

Upvotes: 1

Views: 5738

Answers (1)

akton
akton

Reputation: 14386

Get the PropertyInfo object for the generic argument using:

PropertyInfo myProperty = myGenericType.GetType().GenericTypeArguments[0].GetProperty("myPropertyName");

where "0" is the index of the generic type in the class definition and "myPropertyName" is the name of the property. After that, use it as you would any other PropertyInfo object, for example:

myProperty.GetValue(obj); // Where obj is an instance of the generic type

[Edit: original answer below]

If Y must have a property, constrain the type T to one that must implement an interface that contains that property. For example:

public class MyGenericClass<Y> where Y:IMyInterface

Then cast the generic object to the interface and call the property.

Upvotes: 2

Related Questions