Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

In C# what is the difference between Lists and Arrays?

I noticed in the C# LINQ video " Writing Your First LINQ Query" she begins by instantiating a new list like so:

List<int> numbers = new List<int> {2, 4, 8, 16, 32, 65};

What's the difference between this and:

int[] numbers; = new int[] {2, 4, 8, 16, 32, 65};

What's the difference between arrays and lists, what can one do that the other can't?

Coming from a JavaScript background so I'm only used to arrays and not lists. I also noticed looking through C# docs that <> is used often and I was confused as to what that was before watching this video.

Matt Plumridge
seal-mask
.a{fill-rule:evenodd;}techdegree
Matt Plumridge
Front End Web Development Techdegree Student 9,158 Points

List<string> is class with a private member that is a string[]. The MSDN documentation states this fact in several places. The List class is basically a wrapper class around an array that gives the array other functionality.

The answer of which is faster all depends on what you are trying to do with the list/array. For accessing and assigning values to elements, the array is probably negligibly faster since the List is an abstraction of the array.

1 Answer

I don't know C#, but I do know Java and given their similarities the following should apply for C# as well (as with most OOP languages):

One of the biggest differences is that a List may have various types of implementations. For example, Queues implement the List interface and so do Stacks. Basically Lists (and any type thereof) are data-structures for storing a sequence of data. In a Queue for example there is a "first-in-first-out" sequence, Stacks on the other hand implement a "first-in-last-out" sequence. There are of course other types for this data-structure, such as ArrayList and LinkedList and so on.

Arrays on the other hand are rather simple and don't provide you with the "tools" provided in Lists. Data stored in an array typically stored in that order in memory.

That doesn't mean that Arrays are bad - in fact I tend to use them. If you need more control or a more sophisticated way to control the sequence/order of the data or the relation between them - use Lists.