ArrayList vs List<> in C#

2018-12-31 07:51发布

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

Is it only that List<> has a type while ArrayList doesn't?

11条回答
笑指拈花
2楼-- · 2018-12-31 08:17

It is not only difference. ArrayList members can be accessed via index like ordinary arrays and also ArrayList members can easily sorted in direct and reverse order and two ArrayList can be easily merged, which is not the case with simple List. See more on

http://www.cirvirlab.com/index.php/c-sharp-code-examples/112-c-sharp-arraylist-example.html

查看更多
人间绝色
3楼-- · 2018-12-31 08:20

To me its all about knowing your data. If I am continuing to expand my code on the basis of efficiency, I would have to choose the List option as a way of deciphering of my data w/o the unnecessary step of always wondering about types, especially 'Custom Types'. If the machine understands the difference and can determine on it's on what type of data I'm actually dealing with then why should I get in the way and waste time going thru the gyrations of 'IF THEN ELSE' determinations? My philosophy is to let the machine work for me instead of me working on the machine? Knowing the unique differences of different object code commands goes a long way in making your code as efficient.

Tom Johnson (One Entry ... One Exit)

查看更多
高级女魔头
4楼-- · 2018-12-31 08:26

ArrayList is the collections of different types data whereas List<> is the collection of similar type of its own depedencties.

查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 08:28

ArrayList are not type safe whereas List<T> are type safe. Simple :).

查看更多
大哥的爱人
6楼-- · 2018-12-31 08:29

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<int> list = new List<int>();

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/

enter image description here

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

查看更多
登录 后发表回答