IComparable implementation

I use IComparable to sort the type of typed objects. My question is why does it introduce a person type in int32? It seems that the Sort () array gives each type in the array the type I use for comparison.

Comparable:

public class Person:IComparable { protected int age; public int Age { get; set; } public int CompareTo(object obj) { if(obj is Person) { var person = (Person) obj; return age.CompareTo(person.age); } else { throw new ArgumentException("Object is not of type Person"); } } } 

}

 class Program { static void Main(string[] args) { Person p1 = new Person(); Person p2 = new Person(); Person p3 = new Person(); Person p4 = new Person(); ArrayList array = new ArrayList(); array.Add(p1.Age = 6); array.Add(p2.Age = 10); array.Add(p3.Age = 5); array.Add(p4.Age = 11); array.Sort(); foreach (var list in array) { var person = (Person) list; //Cast Exception here. Console.WriteLine(list.GetType().ToString()); //Returns System.Int32 } Console.ReadLine(); } 
-2
source share
4 answers

Your line:

 array.Add(p1.Age = 6) 

adds the result of the operator p1.Age = 6 to the ArrayList. This value is int 6. There is nothing to do with IComparable or Sort.

+11
source

The best way to implement IComparable is to implement IComparable<T> and pass calls to this implementation:

 class Person : IComparable<Person>, IComparable { public int Age { get; set; } public int CompareTo(Person other) { // Should be a null check here... return this.Age.CompareTo(other.Age); } public int CompareTo(object obj) { // Should be a null check here... var otherPerson = obj as Person; if (otherPerson == null) throw new ArgumentException("..."); // Call the generic interface implementation: return CompareTo(otherPerson); } } 
+7
source

You do not add Faces to the array.

 p1.Age = 6 

is an assignment, and it returns everything that was assigned to the variable / property (in this case 6).

You need to complete the tasks before placing Faces in an array.

If you only want to put items of the same type in a collection, you want to use a typed collection, not an atypical one. That would catch the problem right away.

+4
source

You add person.Age to your administrator, and person.Age is an int.
You should do something like

 Person p1 = new Person(){Age=3}; array.Add(p1); 
+1
source

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


All Articles