Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

IComparable -> using generics gives me error

Status
Not open for further replies.

serializer

Programmer
May 15, 2006
143
SE
I am using the code below. The code that is commented out is when I don't use the generic CompareTo which works. This code gives me error: Failed to compare two elements in the array.

Why does this happen? I would rather use the Generic one.

private void Form1_Load(object sender, EventArgs e)
{
ArrayList arr = new ArrayList();
arr.Add(new POrder());
POrder p2 = new POrder();
p2.Order = 1;
arr.Add(p2);
arr.Sort();
foreach (POrder p in arr)
{
Console.WriteLine(p.Order.ToString());
}
}
}

public class POrder : IComparable<POrder>
{
public int Order = 2;

//#region IComparable Members

//public int CompareTo(object obj)
//{
// POrder emp = (POrder)obj;
// return Order.CompareTo(emp.Order);

//}

//#endregion

#region IComparable<POrder> Members

public int CompareTo(POrder other)
{
return Order.CompareTo(other.Order);
}

#endregion
}
 
I'm just getting into generics myself but I would think it would have to do with the fact you are using an ArrayList without any generic type.

Try:
Code:
   private void Form1_Load(object sender, EventArgs e)
        {
            List<POrder> arr = new List<POrder>();
            arr.Add(new POrder());
            POrder p2 = new POrder();
            p2.Order = 1;
            arr.Add(p2);
            arr.Sort();
            foreach (POrder p in arr)
            {
                Console.WriteLine(p.Order.ToString());
            }
        }
    }
 
Right, you would use List<>, not ArrayList.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top