Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IComparable in C#

I have an object called Shape which contains a public int[,] coordinate { get; set; } field.

I have a separate class which has a collection of Shape objects. At a particular point, I wish to check:

if(shapes.Contains(shape))
{
   // DoSomething
}

So in the Shape class I have added the IComparable reference and inserted the CompareTo method:

public int CompareTo(Shape other)
{
    return this.coordinate.Equals(other.coordinate);
}

I am however getting an error:

Cannot implicitly convert type 'bool' to 'int'

How do I therefore phrase the return so that it returns an int and not a bool as it is doing so at the moment?

UPDATE

If I change the return code to:

return this.coordinate.CompareTo(other.coordinate);

I get the following error mesage:

Error 1 'ShapeD.Game_Objects.Shape' does not implement interface member 'System.IComparable.CompareTo(ShapeD.Game_Objects.Shape)'. 'ShapeD.Game_Objects.Shape.CompareTo(ShapeD.Game_Objects.Shape)' cannot implement 'System.IComparable.CompareTo(ShapeD.Game_Objects.Shape)' because it does not have the matching return type of 'int'. C:\Users\Usmaan\Documents\Visual Studio 2012\Projects\ShapeD\ShapeD\ShapeD\Game Objects\Shape.cs 10 18 ShapeD

like image 858
Subby Avatar asked Aug 06 '13 05:08

Subby


1 Answers

IComparable implies, that two object can be compared in a sense, that you can tell which object has "higher value". It is generally used for sorting purposes. You should override Equals method instead .You should also use Point struct instead of array.

class Shape : IEquatable<Shape>
{
    public Point coordinate { get; set; }

    public bool Equals(Shape other)
    {
        if (other == null) return false;
        return coordinate.Equals(other.coordinate);
    }

    public override bool Equals(object other)
    {
        if (other == null) return false;
        if (ReferenceEquals(this, other)) return true;
        var shape = other as Shape;
        return Equals(shape);
    }

    public override int GetHashCode()
    {
        return coordinate.GetHashCode()
    }
}
like image 185
Nikita B Avatar answered Sep 20 '22 14:09

Nikita B