I have a generic Type as follows
public class TestGeneric
{
public T Data { get; set; }
public TestGeneric(T data)
{
this.Data =
You need to know the closed type of a generic class before you can access its generic members. The use of TestGeneric<>
gives you the open type definition, which cannot be invoked without specifying the generic arguments.
The simplest way for you to get the value of the property is to reflect on the closed type in use directly:
public static void Main()
{
object myObject = new TestGeneric<string>("test"); // or from another source
var type = myObject.GetType();
if (IsSubclassOfRawGeneric(typeof(TestGeneric<>), type))
{
var dataProperty = type.GetProperty("Data");
object data = dataProperty.GetValue(myObject, new object[] { });
}
}
Ahh, sorry for that. It was a simple mistake, the generic version works, of course it must read
var dataProperty = myObject.GetType().GetProperty("Data");
object data = dataProperty.GetValue(myObject, new object[] { });
Oh, stackies... why didn't somebody point me to the dynamic
type?? That's the perfect usage example which makes the code A LOT more readable:
dynamic dynObject = myObject;
object data = dynObject.Data;
With C# 6 and up we can use nameof to improve slightly Paul's answer:
public static void Main()
{
object myObject = new TestGeneric<string>("test"); // or from another source
var type = myObject.GetType();
if (IsSubclassOfRawGeneric(typeof(TestGeneric<>), type))
{
var dataProperty = type.GetProperty(nameof(TestGeneric<object>.Data));
object data = dataProperty.GetValue(myObject);
}
}
Notice that replacing type.GetProperty("Data")
with type.GetProperty(nameof(TestGeneric<object>.Data))
gives you compile time safety (so arguably better than using the dynamic
way as well).
Also using object
as a type parameter is just a way to get access to the property and doesn't have any side effect or particular meaning.