Compile time error: "Cannot convert from B to T1", when working with generics ,constraints and inheritance in C#

Viewed 165

I have a class B which has a method GetSomeB that returns a new instance of its class:

public class B
{
    public B() { }
    public B GetSomeB ()
    {
        return new B();
    }
}

I have a class A which works with generics. The generics must be an object of B or of something inherited from B. I however need the types of attributes X and Y in A to be the specific subclass type and not just type B, so I have used generics T1 and T2:

class A<T1, T2>
        where T1 : B
        where T2 : B
    {
        public T1 X;
        public T2 Y;

        public A(T1 X, T2 Y)
        {
            this.X = X;
            this.Y = Y;
        }

        public A<T1, T2> GetSomeA()
        {
            return new A<T1, T2>(this.X.GetSomeB(), this.Y.GetSomeB());
        }
 }

I am getting compile time errors: Cannot convert from B to T1 and Cannot convert from B to T2 from the line in GetSomeA method in class A How can I work around this?

1 Answers

You could use casts to fix the compile error:

public A<T1, T2> GetSomeA() 
{
      return new A<T1, T2>((T1)this.X.GetSomeB(), (T2)this.Y.GetSomeB());
}
Related