ArrayList vs List<> in C#

后端 未结 12 2130
深忆病人
深忆病人 2020-11-22 04:10

What is the difference between ArrayList and List<> in C#?

Is it only that List<> has a type while ArrayLis

12条回答
  •  温柔的废话
    2020-11-22 05:15

    Using List you can prevent casting errors. It is very useful to avoid a runtime casting error.

    Example:

    Here (using ArrayList) you can compile this code but you will see an execution error later.

    ArrayList array1 = new ArrayList();
    array1.Add(1);
    array1.Add("Pony"); //No error at compile process
    int total = 0;
    foreach (int num in array1)
    {
     total += num; //-->Runtime Error
    }
    

    If you use List, you avoid these errors:

    List list1 = new List();
    list1.Add(1);
    //list1.Add("Pony"); //<-- Error at compile process
    int total = 0;
    foreach (int num in list1 )
    {
     total += num;
    }
    

    Reference: MSDN

提交回复
热议问题