C# use overloaded binary operator (+,*,/,-) operator of base class in derived class

259 views Asked by At

I want to know if there is a way to use an overloaded binary operator for example the + operator of a base class in a derived class. For Example i have following 2 classes:

class Class1
{
    public int num { get; set; }



    public Class1(int a)
    {
        num = a;
    }

    public static Class1 operator +(Class1 a, Class1 b)
    {           
        return new Class1(a.num + b.num);
    }
}

class Class2 : Class1
    {
        int x { get; set; } = 99;
        public Class2(int a):base(a)
        {

        }
         
    }

Class1 overloads the + operator and returns an object of Class1 where the value of num is the sum of the property num of the parameters a and b which are types of the Class1.

Class2 is derived from Class1. The + operation of Class2 works the same way like the + operation of Class1, so i want Class2 use the + operation of Class1. The problem is that the overloaded + operator method expects 2 objects of type Class1 and returns an Object of Class1. So if im trying to do an + operation between 2 objects of Class2 like

Class2 a = new Class2(4);
Class2 b = new Class2(5);
a = a + b;

Im getting the following error: Severity Code Description Project File Line Suppression State

Error CS0266 Cannot implicitly convert type 'Class1' to 'Class2'. An explicit conversion exists (are you missing a cast?)

So i tried to cast it like this:

a = (Class2)(a + b);

but im ending in the following runtime error:

System.InvalidCastException: 'Unable to cast object of type 'TimeSeriesModule.Class1' to type 'TimeSeriesModule.Class2'.

A great solution would be where i can use the overloaded operator of the base class in my derived class and it would be nice if casting wouldn't be a thing but I'm not sure either of these solutions is even possible.

Thanks in advance.

Kind Regards Max

0

There are 0 answers