0
public class ClassWithGeneric<T>
{
}

public class SecondClassWithGeneric<U>
{
    public void getNestedObject()
    {
        //How do I get the type of object T?
    }
}

public class TestProgram
{
   var nestedGenerics = new SecondClassWithGeneric<ClassWithGeneric<ObjectToLoad>>;  
}

public class ObjectToLoad
{
}

The question is how do I get the type of object T? in this case it would return "ObjectToLoad".

2
  • 2
    Incomplete. You don't specify a real connection between ClassWithGeneric and SecondClassWithGeneric. Commented Jul 16, 2014 at 19:09
  • @HenkHolterman, they're nested? Commented Jul 16, 2014 at 19:14

2 Answers 2

3

Not very clear but probably:

public class SecondClassWithGeneric<U, T> 
         where U : ClassWithGeneric<T>   
{
    public T getNestedObject()
    {
        //How do I get the type of object T?
    }
}

or maybe

public class SecondClassWithGeneric<U, T> 
{
    public ClassWithGeneric<T> getNestedObject()
    {
        //How do I get the type of object T?
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

This should give you the type ObjectToLoad but it's also highly prone to error.

public class SecondClassWithGeneric<U>
{
    public void getNestedObject()
    {
         var type = typeof(U).GetGenericArguments()[0];
    }
}

2 Comments

Right, but is that not one .GetGenericArguments()[0] too many?
Yes, one could start from typeof(SecondClassWithGeneric<U>), but it is easier to start typeof(U) like you do. Since .NET 4.5, there is also typeof(U).GenericTypeArguments[0]. In both cases one should check the length of the array before doing attempting to read the 0th entry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.