Hello!
Here is the new code implementing IComparable<Tand IComparable.
If I use List<Tit works fine.
If I instead use ArrayList I get runtime error with the message
"Failed to compare two elements in the array ?"
when the List.Sort() is called.
I just want to find the problem tom this runtime error ?
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
ArrayList list = new ArrayList();
list.Add(new Person("tony", 13));
list.Add(new Person("olle", 23));
list.Add(new Person("stina", 53));
list.Add(new Person("august", 3));
list.Add(new Person("roland", 33));
list.Sort();
foreach (Person pers in list)
Console.WriteLine(pers.Age);
}
}
public class Person : IComparable<Person>
{
string name;
int age;
public Person(string lname, int lage)
{
name = lname;
age = lage;
}
public int Age
{
set {age = value;}
get {return age; }
}
public int CompareTo(Person other)
{
if (other ==null)
return 1;
return this.Age - other.Age;
}
public int CompareTo(object obj)
{
if (obj is Person)
{
Person pers = obj as Person;
return this.Age - pers.Age;
}
else
{
if (obj == null)
return 1;
throw new ArgumentException("Object to compare to is not a
Person object");
}
}
}
}
"Peter Duniho" <Np*********@nnowslpianmk.comskrev i meddelandet
news:op***************@petes-computer.local...
On Sun, 26 Oct 2008 10:15:01 -0700, Tony Johansson
<jo*****************@telia.comwrote:
>Hello!
Yes I noticed that my runtime error disapperar when I used List<T>
instad of
ArrayList.
Yes I also know that it's a better solution to use List<Tinstad of
ArrayList.
But I just want to find out what is causing the error when I use the
ArrayList?
He told you. You've only implemented IComparable<Person>, not
IComparable. He also pointed out a mistake in your comparison method,
which you should also fix.
For future reference, while it's very good that you included the error
message in your question, you should also be specific about _where_ the
message happens. In this case, it's relatively obvious, but you should
get into the habit of being as specific as possible when asking questions.
Pete