Search code examples
c#classgenericsgeneric-programminggeneric-type-argument

Generic type argumented class with generic type argumented Subclass


I have one class with a generic type, like this:

public class Test<T> {
    /*
       Some Properties and Fields
    */
}

Now I need a public Property SubTest{T} in class Test{T} with datatype Test{T}

public class Test<T> {
    /*
       Some Properties and Fields
    */
    public Test<T> SubTest { get; set; }
}

T and U are not the same datatype and SubTest can be null. Is that possible in C#?

Update Or like This?

public class Test {
    /*
       Some Properties and Fields
    */
    public Type ElementType { get; private set; }
    public Test SubTest { get; set; }

    public Test(Type elementType) {
        ElementType = elementType;
    }
}

Solution

  • Your question is a bit inconsistent:

    Now I need a public Property SubTest{T} in class Test{T} with datatype Test{T}

    But your example is different, and now U has been added.

    public class Test<T> 
    {
        public Test<U> SubTest { get; set; }
    }
    

    So to answer your question as-is, replace U with T:

    public class Test<T> 
    {
        public Test<T> SubTest { get; set; }
    }
    

    I think what you are trying to do is to create a generic "test" object, and then have multiple implementations (with different types). I would use interfaces instead, but its the same concept with classes.

    public interface ITest
    {
        // general test stuff
    }
    
    // Type-specific stuff
    public interface ITesty<T> : ITest
    {
         public ITest SubTest { get; set; }    // a sub-test of any type
    }