ArrayList vs List<> in C#

后端 未结 12 2231
深忆病人
深忆病人 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 04:55

    Simple Answer is,

    ArrayList is Non-Generic

    • It is an Object Type, so you can store any data type into it.
    • You can store any values (value type or reference type) such string, int, employee and object in the ArrayList. (Note and)
    • Boxing and Unboxing will happen.
    • Not type safe.
    • It is older.

    List is Generic

    • It is a Type of Type, so you can specify the T on run-time.
    • You can store an only value of Type T (string or int or employee or object) based on the declaration. (Note or)
    • Boxing and Unboxing will not happen.
    • Type safe.
    • It is newer.

    Example:

    ArrayList arrayList = new ArrayList();
    List list = new List();
    
    arrayList.Add(1);
    arrayList.Add("String");
    arrayList.Add(new object());
    
    
    list.Add(1);
    list.Add("String");                 // Compile-time Error
    list.Add(new object());             // Compile-time Error
    

    Please read the Microsoft official document: https://blogs.msdn.microsoft.com/kcwalina/2005/09/23/system-collections-vs-system-collection-generic-and-system-collections-objectmodel/

    Note: You should know Generics before understanding the difference: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/

提交回复
热议问题