IComparable in C #

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

I have a separate class that has a collection of Shape objects. At some point I want to check:

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

So, in the Shape class, I added the IComparable link and inserted the CompareTo method:

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

However, I get the error message:

 Cannot implicitly convert type 'bool' to 'int' 

How do I therefore phrase return to return int rather than bool, since it is doing this at the moment?

UPDATE

If you change the return code to:

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

I get the following error message:

Error 1 'ShapeD.Game_Objects.Shape' does not implement the member of the interface '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 corresponding return type 'int'. C: \ Users \ Usmaan \ Documents \ Visual Studio 2012 \ Projects \ ShapeD \ ShapeD \ ShapeD \ Game Objects \ Shape.cs 10 18 ShapeD

+6
source share
3 answers

IComparable implies that two objects can be compared in a certain sense, that you can say which object has a "higher value". It is commonly used for sorting. Instead, you should override the Equals method. 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.X ^ coordinate.Y; } } 
+3
source

Since you only want to check the equality implementation, the IEquatable interface is not IComparable . IComparable used for sorting purposes.

 public bool Equals(Shape s) { int count=0; int[] temp1=new int[this.coordinate.Length]; foreach(int x in this.coordinate)temp1[count++]=x;//convert to single dimention count=0; int[] temp2=new int[s.coordinate.Length]; foreach(int x in s.coordinate)temp2[count++]=x;//convert to single dimention return temp1.SequenceEqual(temp2);//check if they are equal } 

Note

IEquatable must be implemented for any object that can be stored in the generic else collection; you will also need to override the Object Equals method. Also, as indicated in other ans Point struct applications instead of a multidimensional array

+3
source

To perform a check Contains the need to override the Equals operator in the Shape class.

+2
source

Source: https://habr.com/ru/post/951087/


All Articles