What is the difference between C# array and C# list?

In C#, both lists and arrays are used to store collections of items, but they have some differences in their behavior and usage.

Here are some of the key differences between C# lists and C# arrays:

Size:

Arrays have a fixed size that is set when they are created, while lists can grow or shrink dynamically as items are added or removed.

int[] array = new int[3];
List<int> list = new List<int>();

Console.WriteLine(array.Length);  // Output: 3
Console.WriteLine(list.Count);    // Output: 0

array = new int[5];
list.Add(1);
list.Add(2);
list.Add(3);

Console.WriteLine(array.Length);  // Output: 5
Console.WriteLine(list.Count);    // Output: 3

As you can see, arrays have a fixed size that is set when they are created, while lists can grow or shrink dynamically as items are added or removed.

Accessing Elements:

Arrays are accessed by index, while lists can be accessed using either an index or a foreach loop.

int[] array = new int[] { 1, 2, 3 };
List<int> list = new List<int>() { 1, 2, 3 };

Console.WriteLine(array[1]);  // Output: 2
Console.WriteLine(list[1]);   // Output: 2

foreach (int item in list)
{
    Console.WriteLine(item);
}

for (int i = 0; i < array.Length; i++)
{
    Console.WriteLine(array[i]);
}

Arrays are accessed by index, while lists can be accessed using either an index or a foreach loop.

Type:

Arrays can only store items of the same type, while lists can store items of different types.

int[] array = new int[3];
object[] objectArray = new object[3];
List<int> list = new List<int>();

objectArray[0] = "hello";  // This is allowed
array[0] = "hello";        // This is not allowed
list.Add("hello");         // This is not allowed
list.Add(1);               // This is allowed

Arrays can only store items of the same type, while lists can store items of different types.

Memory Allocation:

Arrays allocate memory for all their elements when they are created, while lists only allocate memory as needed.

int[] array = new int[3];
List<int> list = new List<int>();

Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(array));  // Output: 12
Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(list));    // Output: 16

list.Add(1);
Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(list));    // Output: 16

list.Add(2);
Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(list));    // Output: 16

Arrays allocate memory for all their elements when they are created, while lists only allocate memory as needed.

Initialization:

Arrays need to be initialized with values or set to default values, while lists can be created and used immediately.

int[] array = new int[] { 1, 2, 3 };
List<int> list = new List<int>() { 1, 2, 3 };

Console.WriteLine(array[0]);  // Output: 1
Console.WriteLine(list[0]);   // Output: 1

Arrays need to be initialized with values or set to default values, while lists can be created and used immediately.

Performance:

Arrays generally have better performance than lists when it comes to accessing individual elements, but lists are faster when it comes to adding or removing elements from the collection.

int[] array = new int[1000000];
List<int> list = new List<int>();

Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = 0; i < array.Length; i++)
{
    array[i] = i;
}
stopwatch.Stop();
Console.WriteLine("Array assignment: " + stopwatch.ElapsedMilliseconds);

stopwatch.Restart();
for (int i = 0; i < list.Capacity; i++)
{
    list.Add(i);
}
stopwatch.Stop();
Console.WriteLine("List add: " + stopwatch.ElapsedMilliseconds);

Arrays generally have better performance than lists when it comes to accessing individual elements, but lists are faster when it comes to adding or removing elements from the collection.

When to use array vs list in C#?

In C#, arrays and lists are both used to store collections of items. However, there are some key differences between the two, and which one you use depends on the specific needs of your program.

Here are some factors to consider when deciding whether to use an array or a list in C#:

1. Fixed vs. dynamic size

  • Arrays have a fixed size that must be specified when the array is created. Once the size is set, it cannot be changed.
  • Lists have a dynamic size, which means that items can be added or removed from the list as needed.

If you know exactly how many items you need to store and that number won't change, an array may be the better choice. However, if you need to be able to add or remove items from the collection, a list is likely the way to go.

2. Performance

  • Accessing items in an array is generally faster than accessing items in a list because arrays have a fixed size and are stored in contiguous memory.
  • Inserting or deleting items in an array can be slower than with a list because all items after the insertion or deletion point need to be shifted to accommodate the change.
  • Lists are optimized for inserting or deleting items at arbitrary positions in the list.

If your program needs to perform many random access operations, an array may be more efficient. If you need to perform many insertions or deletions at arbitrary positions, a list may be more efficient.

3. Type safety

  • Arrays in C# are type-safe, meaning that you cannot add an item of the wrong type to an array.
  • Lists are also type-safe, but they can be used with generics to enforce type safety at compile time.

If type safety is a concern, either option should suffice. However, if you need to work with a collection of items of a specific type, generics and lists may be a more elegant solution.

In summary, if you need a fixed-size collection of items with fast random access, an array may be the best choice. If you need a dynamic-size collection that can be easily modified and optimized for insertion and deletion operations, a list is probably the way to go.

In summary, arrays are best used when you know the size of the collection in advance and need to access elements quickly, while lists are more flexible and easier to use when you need to add or remove elements dynamically.

Here is a detailed tutorial on Working with Arrays in C# (code included).


Recommended Free Ebook
Similar Articles