MyClass[] array; List<MyClass> list;
What are the scenarios when one is preferable over the other? And why?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is rare, in reality, that you would want to use an array. Definitely use a
List<T>any time you want to add/remove data, since resizing arrays is expensive. If you know the data is fixed length, and you want to micro-optimise for some very specific reason (after benchmarking), then an array may be useful.List<T>offers a lot more functionality than an array (although LINQ evens it up a bit), and is almost always the right choice. Except forparamsarguments, of course. ;-pAs a counter –
List<T>is one-dimensional; where-as you have have rectangular (etc) arrays likeint[,]orstring[,,]– but there are other ways of modelling such data (if you need) in an object model.See also:
That said, I make a lot of use of arrays in my protobuf-net project; entirely for performance:
byte[]is pretty much essential for encoding;byte[]buffer which I fill before sending down to the underlying stream (and v.v.); quicker thanBufferedStreametc;Foo[]rather thanList<Foo>), since the size is fixed once built, and needs to be very fast.But this is definitely an exception; for general line-of-business processing, a
List<T>wins every time.