When to use List vs Array in C#
Arrays in C# have a fixed size and are slightly more memory-efficient. Lists are dynamic, can grow or shrink, and provide convenient methods like Add(), Remove(), and Contains().
Use arrays when the size is known and won't change, or when maximum performance is critical. Use List<T> for most other scenarios where flexibility matters more than the small performance difference.
Arrays use [] syntax for declaration and initialization. Lists use the generic List<T> class and provide LINQ support out of the box.
C# Example Code
using System;
using System.Collections.Generic;
public class ListVsArray
{
public static void Main(string[] args)
{
// Array - fixed size
int[] numbersArray = new int[5]; // Fixed size of 5
numbersArray[0] = 10;
numbersArray[1] = 20;
numbersArray[2] = 30;
// numbersArray[5] = 40; // Error: IndexOutOfRangeException
Console.WriteLine("Array:");
Console.WriteLine($"Length: {numbersArray.Length}");
Console.WriteLine($"First element: {numbersArray[0]}");
// Array initialization
string[] colorsArray = { "Red", "Green", "Blue" };
Console.WriteLine($"Colors: {string.Join(", ", colorsArray)}");
// List - dynamic size
List<int> numbersList = new List<int>();
numbersList.Add(10);
numbersList.Add(20);
numbersList.Add(30);
numbersList.Add(40); // Can add more elements
numbersList.Add(50);
Console.WriteLine("\nList:");
Console.WriteLine($"Count: {numbersList.Count}");
Console.WriteLine($"First element: {numbersList[0]}");
// List initialization
List<string> colorsList = new List<string> { "Red", "Green", "Blue" };
colorsList.Add("Yellow"); // Easy to add more
Console.WriteLine($"Colors: {string.Join(", ", colorsList)}");
// List methods
colorsList.Remove("Green");
Console.WriteLine($"After removal: {string.Join(", ", colorsList)}");
Console.WriteLine($"Contains Red: {colorsList.Contains("Red")}");
// Converting between them
int[] fromList = numbersList.ToArray(); // List to Array
List<string> fromArray = new List<string>(colorsArray); // Array to List
Console.WriteLine($"\nConverted array: {string.Join(", ", fromList)}");
Console.WriteLine($"Converted list: {string.Join(", ", fromArray)}");
// Performance comparison
Console.WriteLine("\nAccess performance:");
int[] perfArray = new int[1000];
List<int> perfList = new List<int>(1000);
Console.WriteLine("Both have O(1) access time for indexed elements");
Console.WriteLine("Arrays are slightly faster but Lists offer more flexibility");
}
}