Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C#: Class with a variable whose data type varies

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

'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; }
    } 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading