tags:

views:

56

answers:

2

When I write this code, I get an error on the Sort() Method.

       ArrayList al = new ArrayList();
        al.Add("I");
        al.Add("am");
        al.Add(27);
        al.Add("years old");


        foreach (object o in al)
        {
            Console.Write("{0} ", o.ToString());
        }

        al.Sort();
        Console.WriteLine();
        foreach (object o in al)
        {
            Console.Write("{0} ", o.ToString());
        }

Well, I can understand that the Sort Method failed since I included both String and integer in the collection.

But it doesn't error out when I have all strings or all integers. It does the sorting really well.

  1. What is the property of IComparable implementation, that can possibly error out the mixure?
  2. How does it recognize all integers or all strings for sorting?
+2  A: 

It uses the compareTo of the Object. Inside the compareTo, the object will check the type of the compared object and can produce error there like this:

String : IComparable

public int compareTo(Object s) {
  if (!(s is String)) {
    throws new Exception();
  }
  //do the job
}

The sort method of the array will loop through elements of the array and call the compareTo method on each element to compare with other elements

I also recommend you to use generics so you can never accidentially put different kinds of objects inside. Use ArrayList<String>

vodkhang
You mean if (!(s is Int32)) ?
Edgar Sánchez
No I mean if s is not a String, then throw an exception. The example I give is wrong
vodkhang
A: 

You can use a delegate to create a custom sorting. Below, it is sorting custom list of Address based on Address.AddressId

// sort list in descending order
addressList.Sort(delegate(Address a1, Address a2) { return a2.AddressId.CompareTo(a1.AddressId); });

You can create any kind of logic for this, even getting both parameters to delegate as objects and then testing their type, and compare based on that.

Leon