Jason Portnoy
Jason Portnoy

Reputation: 797

Return the generic object, from a generic object

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".

Upvotes: 0

Views: 60

Answers (2)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

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];
    }
}

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273179

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?
    }
}

Upvotes: 3

Related Questions