Home > OS >  I get the same code when overriding C# Equals method. How should I collapse duplicate code?
I get the same code when overriding C# Equals method. How should I collapse duplicate code?

Time:08-21

I have 2 custom sealed classes: Line and ColoredLine. Both implement the IEquals<T> interface. But when I am overriding IEquals method, I get this:

public override bool Equals(object obj) 
{
    if (obj == null) 
    {
        return false;
    }

    if (obj == this) 
    {
        return true;
    }

    if (!(obj is ColoredLine)) 
    {
        return false;
    }

    return this.Equals((ColoredLine)obj);
}

and

public override bool Equals(object obj) 
{
    if (obj == null) 
    {
        return false;
    }

    if (obj == this) 
    {
        return true;
    }

    if (!(obj is Line)) 
    {
        return false;
    }

    return this.Equals((Line)obj);
}

The difference in only a type. Should I collapse it?

CodePudding user response:

I would stick to the MS guidelines

return Equals(obj as ColoredLine);

is short enough

CodePudding user response:

I would let ColoredLine inherit from Line and also use Line.Equals to check if two colored-lines are equal, so like this:

public class Line: IEquatable<Line>
{
    public int Length { get; set; }

    public override bool Equals(object? obj)
    {
        return obj is Line l && this.Equals(l);
    }
    public bool Equals(Line? other)
    {
        return Length == other?.Length;
    }
}

public class ColoredLine: Line, IEquatable<ColoredLine>
{
    public System.Drawing.Color Color { get; set; }

    public override bool Equals(object? obj)
    {
        return obj is ColoredLine cl && this.Equals(cl);
    }
    public bool Equals(ColoredLine? other)
    {
        return base.Equals(other) && Color == other?.Color;
    }
}

Remember that you also should override GetHashCode whenever you override Equals.

  •  Tags:  
  • c#
  • Related