A System.Collections.Generic.List object represents an ordered collection of elements of type T which can increase its size dynamically as new elements are aded. Elements can also be removed from the list.
The capacity of the list starts off at 4 (unless you specify a different capacity in the constructor). When a 5th element is added the capacity is doubled, when a 9th element is added it's doubled again and so forth.
A single dimensional array, T[], also represents an ordered collection of elements of type T but it's size remains fixed once it has been created - i.e. you can't add elements to or remove elements from it. Methods such as Array.Resize which appear to contradict this do in fact create a new array object rather than alter the original one.
Arrays are slightly faster than List's because the latter are more complicated and actually use arrays for their internal storage.
In the case of both lists and arrays, you can access the i'th element using indexer syntax [..].
Both also have methods for finding or checking whether they contain certain elements.
Here's a simple example which illustrates how lists work:
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
List list = new List{1, 2, 3, 4};
Console.WriteLine(list.Capacity); // 4
// add another element
list.Add(5);
Console.WriteLine(list.Capacity); // now 8
// remove 2nd element
list.RemoveAt(1);
// note that removing elements doesn't change capacity
Console.WriteLine(list.Capacity); // still 8
// check if list contains 4
Console.WriteLine(list.Contains(4)); // True
// iterate through and print out remaining elements
VulpesRank #55 · 29.2K reputationPosted Apr 16, 2014, 5:45 AM EDT
Here's a simple example which illustrates how lists work:
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts