[ Home | Syllabus | Course Notes | Assignments | Search]
Here is what happens if you try to print a class for which ToString has not been implemented. It prints out the class name of the object.
Also, as you stated, if I try to use foreach(int MyInt in
MixedArray)
on an ArrayList that has mixed type objects I get an InvalidCastException.
I have attached my code that I used to run these experiments
James Mayor
using System; using System.Collections; public class MixedTypes { static void Main() { try { ArrayList MixedArray = new ArrayList(50); for(int a = 0; a < 20; a++) { if(a < 5) MixedArray.Add(a); else if(a < 11) MixedArray.Add("Element Number {0}" + Convert.ToString(a)); else if(a < 16) MixedArray.Add((float)(a) * 1.0); else if(a < 20) MixedArray.Add( new MyNewClass(a,a*10)); } //This will print out all objects in MixedArray, //printing the class name of the object I created but //did not override the ToString function in Console.WriteLine("\n Output with a for loop"); for(int b = 0; b < 20; b++) { Console.WriteLine(MixedArray[b]); } //This will print out all objects in MixedArray, //printing the class name of the object I created but //did not override the ToString function in Console.WriteLine("\n Output with a foreach loop using object as type"); foreach(object MyObj in MixedArray) { Console.WriteLine(MyObj); } // This Will Throw and Exception because it casts all // objects in MixedArray as int types Console.WriteLine("\n Output with a foreach loop using int as type"); foreach(int MyInt in MixedArray) { Console.WriteLine(MyInt); } } catch(InvalidCastException e) { Console.WriteLine("{0} Exception caught", e); } } } public class MyNewClass { public MyNewClass(int x, int y) { a = x; b = y; } public int a; public int b; }
F1: