Suppose I have a class:
public class Vector
{
public float X { get; set; }
public Vector(float xvalue)
{
X = xvalue;
}
public static Vector operator +(Vector v1, Vector v2)
{
return new Vector(v1.X + v2.X);
}
}
Have a derived class:
public class MyVector : Vector
{
public static MyVector operator +(MyVector v1, MyVector v2)
{
return new MyVector(v1.X + v2.X);
}
public MyVector(float xvalue):base(xvalue)
{
}
}
No if I execute folowing code:
Vector v1 = new MyVector(10); //type MyVector
Vector v2 = new MyVector(20); //type MyVector
Vector v3 = v1 + v2; //executed operator is of Vector class
Here is executed Vector’s + operator, but the type of v1 and v2 is MyVector, so v3 is Vector type at this point.
Why this happens?
Because the type of the variables
v1andv2areVector, notMyVector. Operator overloads are static methods that are resolved by the compiler at compile-time, not at runtime; they cannot be overridden.v1andv2will have to be typedMyVectorfor the compiler to select the overload defined in theMyVectorclass.Optionally, define a method
public virtual Vector Add(Vector other)on theVectorclass and haveMyVectoroverride it. Then call this method from theoperator+method ofVectorand this will work as you expected. (MyVectorwould then not need to defineoperator+itself.)