0

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;
    }
}
Fabter
  • 3
  • 3

2 Answers2

2

U it not defined so it cannot be used like the. You need to create type parameter in the class, or use a specific type, for example string:

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

      public Test<T,U> SubTest { get; set; }
    }
Radin Gospodinov
  • 2,313
  • 13
  • 14
0

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
}
  • Yes you are right, it was a bit inconsistent. Thanks for the reply, I had ever tried with interfaces, but not like you. Thanks – Fabter Jun 09 '16 at 08:48