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 as elements are added and removed, whereas an array is a fixed-size sequential collection of the same type of elements.

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 that cannot be modified during execution. Array elements are accessed using numeric indexes and start at zero. The default value for numeric array items is zero, while the default value for reference array elements is null.

The array is in the System.Array namespace. It must be specified in brackets[], with the type of variables it will carry ( integer, string, etc. ) and the name of the array.
The following is an example of how to define an array of integers with the name intArray:

Create an Array

int[] intArray = new int[5]; // Array having a length of 5
//or
int[] intArray = new int[] {10, 20, 30, 40, 50 };
C# Array
C# Array

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 search, sort, manipulate, add, and remove elements from the collection of strongly typed objects.
C# List has so many additional characteristics, such as the ability to resize dynamically when an element is added or removed.

Please check my previous blog for more information about the list: 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

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.5 2 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Nelson
Nelson
4 months ago

Your post was really an excellent resource for getting a better understanding about the array and list.