Murat
Murat

Reputation: 803

How to get generic type from object type

My Classes are;

class BaseClass
{

}

class DerivedClass1 : BaseClass
{

}

class GenericClass<T>
{

}

class DerivedClass2 : BaseClass
{
    GenericClass<DerivedClass1> subItem;
}

I want to access all fields of DerivedClass2 class. I use System.Reflection and FieldInfo.GetValue() method;

Bu I cant get subItem field. FieldInfo.GetValue() method return type is "object". And I cant cast to GenericClass<DerivedClass1> or I cant get DerivedClass1 type. I try this with BaseClass

BaseClass instance = FieldInfo.Getvalue(this) as GenericClass<BaseClass>;

but instance is null. How to get instance with type or how to get only type?

Upvotes: 1

Views: 2282

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160902

I'm not sure exactly what you want to achieve, but his works for me:

var foo = new DerivedClass2();
var result = typeof(DerivedClass2).GetField("subItem", 
                                            BindingFlags.NonPublic | 
                                            BindingFlags.Instance)
                                  .GetValue(foo);
var genericClassField = result as GenericClass<DerivedClass1>;

genericClassField is of type GenericClass<DerivedClass1> - of course you have to assign it a value before doing this, otherwise result will be null, for this I added a constructor to your DerivedClass2 that does just that:

class DerivedClass2 : BaseClass
{
    GenericClass<DerivedClass1> subItem;

    public DerivedClass2()
    {
        subItem = new GenericClass<DerivedClass1>();
    }
}

Edit:

To find out the type of result at runtime you could do the following:

var foo = new DerivedClass2();
var result = typeof(DerivedClass2).GetField("subItem", 
                                            BindingFlags.NonPublic | 
                                            BindingFlags.Instance)
                                  .GetValue(foo);
Type myType = result.GetType().GetGenericArguments()[0];

In the example this would return the type DerivedClass1. Also I think this msdn article might be relevant.

Upvotes: 2

Related Questions