Saturday 3 January 2015

ArrayList class is not type-safe, why?


A)ArrayList class is not type-safe because it can store any object.
Ex:
var integers = new ArrayList();
integers.Add(1);
integers.Add(2);
integers.Add("3");

for (int i = 0; i < integers.Count; ++i) {
    int integer = (int)integers[i];
    // do something
}


The above will compile because the value "3", even though it's a string and not an integer, can legally be added to an ArrayList since String derives (like Int32) from Object. However, it will throw an InvalidCastException when you try to set integer to (int)integers[2] because a String cannot be cast to an Int32.