C# Array vs List: When should you use an array or a List?

C# Array vs List: A List<T> is a generic collection that can resize automatically when you add or remove elements, whereas an array is a fixed-size sequential collection that can hold elements of the same type.

C# Array VS List
C# Array VS List

Array

C# Array: Arrays are strongly typed collections of the same data type with a fixed length, meaning you cannot change their size once created. Array elements can be accessed using numeric indexes, starting from zero.

So, the first item in the array is at index 0, and the second item is at index 1, and so on.

The default value for numeric array items is zero, while the default value for reference array elements is null. 

The array class is available in the System.Array namespace. To define an array, you use square brackets “[]” and specify the type of data the array will hold (e.g., integers, strings) and give the array a name.

For example, let’s create an array of integers called intArray:

Create an Array

// Create an integer array called 'intArray' with a length of 5
int[] intArray = new int[5];



// Alternatively, you can initialize the array with specific values like this:


int[] intArray = new int[] {10, 20, 30, 40, 50};


// Now, 'intArray' contains the following values at different indexes:
// Index 0: 10
// Index 1: 20
// Index 2: 30
// Index 3: 40
// Index 4: 50
C# Array
C# Array

In this example, we created an array of integers called intArray with a capacity of 5 items. IntArray can hold five integers, and we can access each element using the indexes 0 to 4.

Access the elements of an Array

You can create a string array with the following syntax:

using System;
namespace CSharpArrayExample
{
    public class CSharpArrayExample
    {   
        static void Main(string[] args)
        {
            // Declare an array
            string[] fruitsName = { "Apple", "Orange", "Banana", "Grapes"};

            // Access the elements of an Array using index
            Console.WriteLine(fruitsName[0]); // Output: Apple

            // Access the elements using for loop
            for(int index = 0; index < fruitsName.Length; index ++)
            {
                Console.WriteLine(fruitsName[index]);
            }

            Console.ReadKey();
        }
        //Output:
        // Apple
        // Orange
        // Banana
        // Grapes
    }
}

C# List

List<T>: In C#, the List is a generic type used to represent the collection of strongly typed objects that can be accessed via index or loops. The List class is available in the  System.Collection.Generic  namespace.

It allows you to perform various operations such as searching, sorting, manipulating, adding, and removing elements from the collection.
A great thing about the List is that it can change its size dynamically, which means it can grow or shrink as you add or remove items.

If you want to know more about the List class and how to use it in C#, you can check out my previous article, “C# List Class“.

Syntax

The following is the syntax for declaring a generic List< T >. The parameter T in the List represents the type of item in the list, which can be int, long, string, or any user-defined object.

List<T> myList = new List<T>();

C# List<T> example

The following is an example of a List in C#

using System;
using System.Collections.Generic;
namespace CSharpListExample
{
    public class CSharpArrayExample
    {   
        static void Main(string[] args)
        {
            // Declare a generic List of string type
            List<string> fruitsName = new List<string>();
           // Add items in the List

            fruitsName.Add("Apple");
            fruitsName.Add("Orange");
            fruitsName.Add("Banana");
            fruitsName.Add("Grapes");
            
            // Access the elements of a List using index
            Console.WriteLine(fruitsName[0]); // Output: Apple

            // Access the list elements using for loop
            for(int index = 0; index < fruitsName.Count; index ++)
            {
                Console.WriteLine(fruitsName[index]);
            }

            Console.ReadKey();
        }
        //Output:
        // Apple
        // Orange
        // Banana
        // Grapes
    }
}

C# Array vs List Comparison

ParametersC# ListC# Array
1. LengthA list in C# can be dynamically resized when items are added or removed.The size of an array is fixed, therefore it can only store a fixed number of elements of the same data type.
2. NamespaceC# List class comes under the System.Collection.Generic namespaceArray belongs to the System.Array namespace
3. Memory
List memory is dynamic and random.
A list occupies more memory than an Array since each node defined in the List has its own memory set.
Array memory is static and continuous.
Arrays are memory efficient.
4. UsageA list is useful when elements are frequently added and removed.Arrays are handy when you have a fixed number of elements that are unlikely to change and want to access them frequently in a non-sequential way.
5. SpeedSlower in Execution.An array is faster in Execution.
6. Memory managementWith C# List, there is no memory wastage.Memory wastage is a problem with arrays.
Many of the memory blocks assigned to an array stay unused until new items are added after fixed-sized memory has been allocated. Furthermore, they can’t be assigned to other processes, which leads to memory waste.
7. Memory Structure In C# List, Non-Contiguous Memory Allocation is performed.
Non-Contiguous Memory Allocation separates the process into various blocks, which are subsequently placed in different address spaces of the memory depending on memory space availability. Non-contiguous memory allocation is demonstrated by paging and segmentation.
In C# Array, Contiguous Memory Allocation is performed.
The contiguous Memory Allocation technique allocates a single contiguous block of memory to a process based on its requirements. The memory space is divided into fixed-sized partitions, and each partition is assigned to just one process.
C# Array vs List
Array-Contiguous Memory Allocation
Array-Contiguous Memory Allocation

Difference between C# Arrays and Lists:

Definition:

  • An array is a fixed-size collection that stores elements of the same data type in contiguous memory locations.
  • A list is a dynamic-size collection that can store elements of the same data type and automatically resizes itself as elements are added or removed.

Flexibility:

  • An array is less flexible, as its size cannot be changed after creation. You need to create a new array with a different size if you want to change it.
  • The list is more flexible, as you can add or remove elements without worrying about the size.

Performance:

  • Arrays generally perform better for fixed-size collections due to contiguous memory and direct indexing.
  • Lists might have a slight performance overhead due to dynamic resizing, but for most use cases, the difference is negligible.

Initialization:

  • Elements in an array can be directly initialized during declaration.
  • Elements in a list need to be added one by one, or you can initialize it with an existing collection.

Namespace:

  • Arrays are part of the C# language and don’t require any additional namespace.
  • Lists are part of the System.Collections.Generic namespace, so you need to import it.

Index Access: 

  • You can access elements in an array using index notation (e.g., array[index]).
  • Like arrays, you can access elements in a list using index notation (e.g., list[index]).

Element Types: 

  • Arrays can only hold elements of the same type (homogeneous).
  • Lists can also hold elements of the same type (homogeneous) but can also hold different types using generics.

When to Use:

  • Use Arrays when you know the exact size of the collection in advance and don’t need to change it frequently.
  • Use Lists when you want a flexible collection that can grow or shrink as needed or when you need additional methods for data manipulation.

References: C# Array, C# List

I hope you enjoyed reading this article “C# array vs list“. If you find something incorrect or wish to offer more information regarding the topic addressed here, please leave a comment below.

FAQs

Q: What is the difference between an array and a list in C#?

In C#, an array is a fixed-size collection of elements of the same type, whereas a list is a dynamic collection that can grow or shrink in size. Arrays have a predetermined length, while lists can be modified by adding or removing elements.

Q: How do I declare and initialize an array in C#?

To declare an array in C#, you specify the type of elements it will hold, followed by square brackets ([]).
For example, to declare an array of integers named “myArray,” you can use the syntax: int[] myArray; To initialize the array with specific values, you can use the following syntax:

int[] myArray = {1, 2, 3, 4, 5};

Q: How do I declare and initialize a list in C#?

To declare and initialize a list in C#, you must include the System.Collections.Generic namespace. First, you declare a list by specifying the type of elements it will contain, followed by the name.

For example, to declare a list of strings named “myList,” you can use the syntax: List myList;
To initialize the List, you can use the following syntax:
List myList = new List {"Apple," "Banana," "Mango"};

Q: Can you change the size of an array after it is created?

No, the size of an array in C# is fixed once it is created. You cannot change the length of an array once it’s defined.

Q: Can I change the size of a list after it is created?

Yes, one of the main advantages of a list in C# is its dynamic nature. You can easily add or remove elements from a list using methods like Add, Remove, Insert, and Clear.

Q: When should I use an array?

Arrays are useful when you know the exact number of elements you need, and that number won’t change. They provide efficient random access to elements and can be useful for operations that require fixed-size collections.

Q: When should I use a list?

Lists are preferable when you need a collection that can grow or shrink dynamically. They are helpful when the number of elements is not known in advance or may change over time. Lists provide convenient methods for manipulating elements.

Q: Which one is faster, an array or a list?

Generally, arrays are slightly faster than lists because they have a fixed size and don’t require additional memory allocations. However, the performance difference is usually negligible unless you deal with a large collection of elements.

Q: Can I convert an array to a list and vice versa?

Yes, you can convert an array to a list using the ToList() method of the System.Linq namespace.
For example, List myList = myArray.ToList();
To convert a list to an array, you can use the ToArray() method. For example,
int[] myArray = myList.ToArray();

Q: Are there any other collection types in C#?

Yes, C# provides various collection types, such as dictionaries, queues, stacks, and more. These collections have different characteristics and are suitable for different scenarios. Choosing the appropriate collection type is essential based on your specific needs.

Articles to Check Out:

c20e93cf99b4a0eb1e4a099de6c2c300?s=250&r=g
4.7 3 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments