Valid reason to overload an Operator?

public struct Size
{
    public Size(double x, double y, double z) : this()
    {
        X = x;
        Y = y;
        Z = z;
    }

    public Size(double size)
    {
        X = Y = Z = size;
    }

    public double X { get; set; }
    public double Y { get; set; }
    public double Z { get; set; }

    public override string ToString()
    {
        return $"{{ X = {X}, Y = {Y}, Z = {Z} }}";
    }
}

Arithmetic

Now I want to add two sizes:

var s1 = new Size(5);
var s2 = new Size(5);
var s3 = s1 + s2;

To do that I'd have to override an operator.

I also want to be able to add a number without making a size first, like Size s4 = s3 + 10;, so we need another operator for that.

public static Size operator +(Size s1, Size s2)
{
    return new Size(s1.X + s2.X, s1.Y + s2.Y, s1.Z + s2.Z);
}
public static Size operator +(Size size, double add)
{
    return new Size(size.X + add, size.Y + add, size.Z + add);
}

Equality.

VS also provides a way to help you override equality; in this case we can agree that the uniqueness of a Size object is reliant on the X, Y and Z values.

By default Equals will do a Reference comparison, which means even if two Size objects have the same values s1.Equals(s2) will return false - ie the variables do not point to the same object in memory.

So we want to override the Object.Equals method, and we want to add == and != operators. If you've copy-pasted the Size class to VS you can right-click the class, select the light-bulb and choose "generate equals..." then choose OK.

Now it's possible to use == on two Size objects which will make a call to the strongly typed Equals method and do an X,Y,Z comparison.

If the Size is boxed, ie, you created it like this: object s1= new Size(10); and then try to compare it with s1.Equals(s2);, the call will be to the base Object.Equals method which by default does a Reference comparison, not a value comparison. But since we override it, we yet again return the result of our strongly typed Equals method.

This ensures the == operator and Equals method return the same result.

Not doing this might indeed confuse developers as depending on if you make an Equals call, an operator == comparison they can return different results.

/r/csharp Thread