Compare a List with an Array (in .NET)

curiouswebster
curiouswebster used Ask the Experts™
on
Compare a List with an Array (in .NET)

Please list the pros and cons of each.

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
Both are type safe.  A List has methods that are used to control the internal structure (Add, Remove, Insert, InsertAt, etc.) where as arrays have to be manipulated by index.  It should be noted, however, that a List's internal collection *is* an array.

They are both Enumerable's meaning that you can use LINQ when working with them.

-saige-
Commented:
Here is useful threads for you

Array versus List<T>: When to use which?

Should I use a list or an array?

I would always use List, unless any method is expecting array as param
curiouswebsterSoftware Engineer

Author

Commented:
I thought that an ArrayList automatically up-typed anything you add to it to type Object, and used boxing and unboxing to do so. This means the compiler does not enforce the type you pass in, like a generic list List<> does for you at compile time.

Secondly, an Array (versus an ArrayList) seems even more un-disciplined. It seems you can pile in data of any type, and even more arrays. It then is the job of the programmer to query that array before addressing a cell directly.
ǩa̹̼͍̓̂ͪͤͭ̓u͈̳̟͕̬ͩ͂̌͌̾̀ͪf̭̤͉̅̋͛͂̓͛̈m̩̘̱̃e͙̳͊̑̂ͦ̌ͯ̚d͋̋ͧ̑ͯ͛̉Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
I thought that an ArrayList automatically up-typed anything you add to it to type Object, and used boxing and unboxing to do so.
ArrayList is not strongly typed, no. Everything goes into it as type object. Only value types are boxed/unboxed. Nobody these days suggests using an ArrayList for anything. Generic collections are the modus operandi.

This means the compiler does not enforce the type you pass in, like a generic list List<> does for you at compile time.
Correct.

It seems you can pile in data of any type, and even more arrays. It then is the job of the programmer to query that array before addressing a cell directly.
Arrays are strongly typed. If you declare an array of ints, you can't subsequently stick a string into one of its slots. Yes it is the job of the programmer to be able to retrieve things from the list, as the developers of the List class themselves had to do (since a List uses an array under the hood).
curiouswebsterSoftware Engineer

Author

Commented:
thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial