Shane
Shane

Reputation: 1216

Getting generic type from the DeclaringType of a nested type in C# with reflection

Say I have the following class structure:

public class Outer<T>
{
    public class Inner<U>
    {
    }
}

And some code:

var testType = typeof(Outer<string>.Inner<int>);

How can I get the constructed generic type typeof(Outer<string>), or the value of the generic typeof(string) from the testType variable?

Upvotes: 3

Views: 755

Answers (1)

D Stanley
D Stanley

Reputation: 152566

Interesting - it seems that the outer type's generic argument is projected to the inner type:

var testType = typeof(Outer<string>.Inner<int>);              
var outerType = testType.DeclaringType;                       
var outerTypeGenericParam = outerType.GetGenericArguments();
var testTypeGenericParam = testType.GetGenericArguments();
Console.WriteLine(outerType);                                 // Test+Outer`1[T] 
Console.WriteLine(outerTypeGenericParam[0]);                  // T
Console.WriteLine(testTypeGenericParam[0]);                   // System.String
Console.WriteLine(testTypeGenericParam[1]);                   // System.Int32

so the one-liner in your case would be:

testType.GetGenericArguments()[0]

Upvotes: 6

Related Questions