using System.Collections;
public static void Main()
ArrayList list = new ArrayList();
list.Add(new Person("Rual", 30));
list.Add(new Person("Donna", 25));
list.Add(new Person("Mary", 27));
list.Add(new Person("Ben", 44));
Console.WriteLine("Unsorted people:");
for (int i = 0; i < list.Count; i++)
Console.WriteLine("list["+i+"]"+ (list[i] as Person).Name + ((list[i] as Person).Age));
"People sorted with default comparer (by age):");
for (int i = 0; i < list.Count; i++)
Console.WriteLine("(list[i] as Person).Name" + ((list[i] as Person).Age));
"People sorted with nondefault comparer (by name):");
list.Sort(PersonComparerName.Default);
for (int i = 0; i < list.Count; i++)
Console.WriteLine("{(list[i] as Person).Name}" + ((list[i] as Person).Age));
public class Person : IComparable
public Person(string name, int age)
public int CompareTo(object obj)
Person otherPerson = obj as Person;
return this.Age - otherPerson.Age;
throw new ArgumentException(
"Object to compare to is not a Person object.");
public class PersonComparerName : IComparer
public static IComparer Default = new PersonComparerName();
public int Compare(object x, object y)
if (x is Person && y is Person)
return Comparer.Default.Compare(
((Person)x).Name, ((Person)y).Name);
throw new ArgumentException(
"One or both objects to compare are not Person objects.");