How to access generic property without knowing the closed generic type

Posted by Martin Booka Weser on Stack Overflow See other posts from Stack Overflow or by Martin Booka Weser
Published on 2011-01-04T10:35:26Z Indexed on 2011/01/04 10:54 UTC
Read the original article Hit count: 412

Filed under:
|
|
|

I have a generic Type as follows

public class TestGeneric<T>
{
    public T Data { get; set; }
    public TestGeneric(T data)
    {
        this.Data = data;
    }
}

If i have now an object (which is coming from some external source) from which i know that it's type is of some closed TestGeneric<>, but i don't know the TypeParameter T. Now I need to access the Data of my object. Problem is that i can't cast the object, since i don't know exactly to which closed TestGeneric.

I use

// thx to http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class
private static bool IsSubclassOfRawGeneric(Type rawGeneric, Type subclass)
{
    while (subclass != typeof(object))
    {
        var cur = subclass.IsGenericType ? subclass.GetGenericTypeDefinition() : subclass;
        if (rawGeneric == cur)
        {
            return true;
        }
        subclass = subclass.BaseType;
    }
    return false;
}

to make sure, my object is of the generic type. The code in question is as follows:

public static void Main()
{
    object myObject = new TestGeneric<string>("test"); // or from another source
    if (IsSubclassOfRawGeneric(typeof(TestGeneric<>), myObject.GetType()))
    {
        // the following gives an InvalidCastException
        // var data = ((TestGeneric<object>)myObject).Data;

        // if i try to access the property with reflection
        // i get an InvalidOperationException
        var dataProperty = typeof(TestGeneric<>).GetProperty("Data");
        object data = dataProperty.GetValue(myObject, new object[] { });
    }
}

I need the Data regardless of its type (well, if i could ask for its type using GetType() would be fine, but not necessary) since i just want to dump it in xml using ToString().

Any suggestions? Thanx.

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection