I’m trying to define a class with a variable named x, whose type matches some generic T. This is easy to achieve:
public class Test<T>{
public T x{get; set;}
}
The problem is that I would like to be able to talk about Test instances with different Ts simultaneously, such as in declaring a List<Test> having elements of types Test<T>, Test<S>, etc. Here’s what I tried:
public interface ITest{
object x {get; set;}
}
public interface ITest<T> : ITest{
T x {get; set;}
}
public class Test<T> : ITest<T>{
public T x {get; set;}
}
This has the effect of hiding x, but what I’m really trying to do is "be more specific" about the type that x has. The error from the above is:
'Test<T>' does not implement interface member 'ITest.x'. 'Test<T>.x' cannot implement 'ITest.x' because it does not have the matching return type of 'object'
Is there some way to downcast the type that x has in ITest<T>?
>Solution :
You were on the right track. Your only problem is that ITest.x has the same name as Test.x. If you make the properties have different names then Test can implement ITest:
public interface ITest
{
object untypedX { get; set; }
}
public interface ITest<T> : ITest
{
T x { get; set; }
}
public class Test<T> : ITest<T>
{
public T x { get; set; }
/// <inheritdoc />
public object untypedX { get=>x; set=>x=(T)value; }
}