I am implmenting the IComparable to sort like typed objects. My question is why does it cast type person to int32? The array's Sort() seems to cast each type in the array to the type that I am using 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();
}