Search code examples
.netarrayliststrong-typingtypesafe

Is Arraylist is typesafe or strongly typed?


I don't know what exactly the difference between "Strongly typed" and "Type safety" is!

Could you please clarify this in a simple language?

Suppose we are using Arraylist, but I am unable to conclude it is typesafe or strongly typed. or can we use it as both.?


Solution

  • An ArrayList is not typesafe. What this means is that ArrayList can be assigned a value of any type:

    ArrayList myList = new ArrayList();
    myList.Add("this is a string");
    myList.Add(19); //Notice that this is an int, but it doesn't throw an error!
    

    This is an issue because when you go to use the list, you don't know the types that are in the list. The chances of having an error thrown are very high.

    Avoid using ArrayLists! Use a generic list instead, such as List<T>