invalid casting exception

I have the following code and I'm getting an invalid casting exception on i on the for loop can someone explain>?

 class MyObject : IComparable
    {
        public int ID { get; set; }

        public int CompareTo(object obj) {
            MyObject obj1 = obj as MyObject;
            return this.ID.CompareTo(obj1.ID);
        
            }
    }

Open in new window


 static void Main(string[] args)
        {

            //int[] myset = new int[5] { 1, 3, 4, 5, 6 };

         //   ArrayList myArray = new ArrayList();
         //   myArray.Add(2);
         //   myArray.Add(10);
         //   myArray.Add(5);
         //   myArray.Add(3);

            ArrayList myList = new ArrayList();
            myList.Add(new MyObject() { ID = 4 });
            myList.Add(new MyObject() { ID = 200 });
            myList.Add(new MyObject() { ID = 10 });
            myList.Sort();

            foreach (int i in myList) {
                Debug.WriteLine(i.ToString());
           
            }
yguyon28Asked:
Who is Participating?
 
trinitrotolueneConnect With a Mentor Director - Software EngineeringCommented:
you probably want to do this:

 foreach (MyObject i in myList) {
                Debug.WriteLine(i.ID.ToString());
}

Open in new window

)
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
it must be like this:
 public int CompareTo(MyObject obj)
 {
       return this.ID.CompareTo(obj.ID);
 }
0
 
AndyAinscowConnect With a Mentor Freelance programmer / ConsultantCommented:
foreach (int i in myList)
myList is a list of MyObject not of int - hence the error

it should be
foreach (MyObject i in myList)
but then I don't know what you want to do with the line after (Debug.WriteLine)
0
All Courses

From novice to tech pro — start learning today.