Dynamic Arrays in C# with Examples

In this C#.Net tutorial, I will explain “Dynamic Arrays in C# with Examples“. Here we will learn:

  • What is a dynamic array in C#?
  • How to Declare and Initialize a Dynamic Array in C#?
  • Adding and Removing Elements from C# dynamic array
  • Loop through all elements in a dynamic array in c#.net.
  • Insert elements into a dynamic array
  • Searching in a Dynamic Array in C#
  • Sorting and Reversing C# dynamic array

We will cover everything with real examples in C#.Net. All the demos I am doing in a C#.Net Windows application.

What is a Dynamic Array in C#.Net?

A dynamic array in C# is essentially an array that can grow and shrink in size during runtime. Unlike traditional arrays, which have a fixed size once they are declared, dynamic arrays can adjust their size as elements are added or removed.

In C#, the List<T> class from the System.Collections.Generic namespace provides the functionality of a dynamic array. It allows for efficient additions, and removals, and contains various helpful methods to manipulate data.

How to Declare and Initialize a Dynamic Array in C#?

Before you can use a dynamic array, you need to include the appropriate namespace:

using System.Collections.Generic;

Now, to declare a dynamic array of strings, for instance, you’d do something like this:

List<string> cities = new List<string>();

Adding and Removing Elements from C# Dynamic Array

With your dynamic array initialized, adding and removing elements is straightforward.

Adding Elements:

cities.Add("New York");
cities.Add("Los Angeles");
cities.Add("Chicago");

Removing Elements:

cities.Remove("Los Angeles"); // Removes the first occurrence of "Los Angeles"

You can also remove an element at a particular index using the RemoveAt method:

cities.RemoveAt(1); // Removes the element at index 1

Traversing the Dynamic Array

To loop through all the elements in our dynamic array, you can use a simple foreach loop:

foreach (string city in cities)
{
    Console.WriteLine(city);
}

C# Dynamic Array Example

Here is a complete example of a C# dynamic array.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Declare and initialize a dynamic array of strings
        List<string> cities = new List<string>();

        // Add some USA city names to the dynamic array
        cities.Add("New York");
        cities.Add("Los Angeles");
        cities.Add("Chicago");
        cities.Add("Houston");
        cities.Add("Phoenix");

        // Display the cities
        Console.WriteLine("USA Cities:");
        foreach (string city in cities)
        {
            Console.WriteLine(city);
        }

        // Remove a city
        cities.Remove("Houston");

        // Display the updated list
        Console.WriteLine("\nUpdated List (After Removing Houston):");
        foreach (string city in cities)
        {
            Console.WriteLine(city);
        }
    }
}

Once you run the above code, you can see the output below:

Dynamic Arrays in C# with Examples

Now we will see some more examples related to C# Dynamic Arrays.

Accessing Elements in a List<T> in C#

Here I will show you different ways to access elements from dynamic arrays.

In C#, a List<T> behaves similarly to an array when it comes to accessing elements, albeit with some additional functionalities provided by built-in methods.

Here is a complete example of how to access elements in a dynamic array in c# with a code explanation.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Declare and initialize a dynamic array of strings
        List<string> cities = new List<string>
        {
            "New York", "Los Angeles", "Chicago", "Houston", "Phoenix"
        };

        // Accessing elements using index
        Console.WriteLine("First city: " + cities[0]);
        Console.WriteLine("Third city: " + cities[2]);

        // Accessing elements using methods
        string firstCity = cities.Find(city => city.StartsWith("N"));
        Console.WriteLine($"First city that starts with 'N': {firstCity}");

        int positionOfHouston = cities.IndexOf("Houston");
        if (positionOfHouston != -1)
        {
            Console.WriteLine($"Houston is at position: {positionOfHouston}");
        }
        else
        {
            Console.WriteLine("Houston is not in the list.");
        }
        
        // Using the FindLast method
        string lastCityWithO = cities.FindLast(city => city.Contains("o"));
        Console.WriteLine($"Last city that contains the letter 'o': {lastCityWithO}");
    }
}

Once you run the code, you can see the output like below:

First city: New York
Third city: Chicago
First city that starts with 'N': New York
Houston is at position: 3
Last city that contains the letter 'o': Phoenix
  1. By Index: The most straightforward way to access an element in a List<T> is by using its index, just like with arrays. In the example, cities[0] returns “New York”, which is the first city in the list.
  2. Using Find: The Find method searches for the first item that matches the provided predicate. In our case, we used a lambda expression to find the first city that starts with the letter “N”.
  3. Using IndexOf: The IndexOf method returns the zero-based index of the first occurrence of a specified item in the list. If the item is not found, it returns -1.
  4. Using FindLast: The FindLast method retrieves the last occurrence that satisfies the provided predicate. In the example, we find the last city containing the letter “o”.

Inserting Elements in a List<T> in C#

The List<T> class in C# provides a handy method named Insert to place an element at a specific position, pushing the subsequent elements back. Let us see a complete example of how to insert elements to a dynamic array in C#.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Declare and initialize a dynamic array of strings
        List<string> cities = new List<string>
        {
            "New York", "Los Angeles", "Chicago"
        };

        Console.WriteLine("Original List of Cities:");
        DisplayCities(cities);

        // Insert a city at the beginning (position 0)
        cities.Insert(0, "San Francisco");
        Console.WriteLine("\nAfter Inserting 'San Francisco' at the beginning:");
        DisplayCities(cities);

        // Insert a city in the middle (position 2)
        cities.Insert(2, "Dallas");
        Console.WriteLine("\nAfter Inserting 'Dallas' in the middle:");
        DisplayCities(cities);

        // Insert a city at the end using the Count property
        cities.Insert(cities.Count, "Phoenix");
        Console.WriteLine("\nAfter Inserting 'Phoenix' at the end:");
        DisplayCities(cities);
    }

    static void DisplayCities(List<string> citiesList)
    {
        foreach (var city in citiesList)
        {
            Console.WriteLine(city);
        }
    }
}

Once you run the code, you can see the output like below:

Original List of Cities:
New York
Los Angeles
Chicago

After Inserting 'San Francisco' at the beginning:
San Francisco
New York
Los Angeles
Chicago

After Inserting 'Dallas' in the middle:
San Francisco
New York
Dallas
Los Angeles
Chicago

After Inserting 'Phoenix' at the end:
San Francisco
New York
Dallas
Los Angeles
Chicago
Phoenix
  1. At the Beginning: To insert an element at the beginning of the list, we specify the index 0 as the first parameter to the Insert method.
  2. In the Middle: If you want to insert an element in the middle, simply provide the desired index. In our example, “Dallas” is inserted at index 2, pushing “Los Angeles” and “Chicago” one position back.
  3. At the End: Though you could use the Add method to insert an element at the end, for demonstration purposes, we used the Insert method with the Count property of the list to append “Phoenix” at the end.
  4. Beyond the Bounds: Note that while the Insert method allows you to place an element from index 0 up to Count (inclusive), trying to insert beyond this range will throw an ArgumentOutOfRangeException.

Searching in a Dynamic Array in C#

Searching in dynamic arrays (represented by List<T> in C#) is a frequent operation, and fortunately, C# provides various methods to facilitate this.

You can use a simple loop to go through each element and find what you’re looking for, but the List<T> class provides built-in methods to make the task more concise and expressive.

Methods for Searching:

  1. Contains: Determines whether an element exists in the list.
  2. IndexOf: Finds the index of the first occurrence of a specified item.
  3. LastIndexOf: Finds the index of the last occurrence of a specified item.
  4. Find: Retrieves the first item that satisfies a given condition.
  5. FindLast: Retrieves the last item that satisfies a condition.
  6. FindAll: Returns all the items that match the provided predicate.
  7. FindIndex: Returns the index of the first item matching the provided predicate.
  8. FindLastIndex: Returns the index of the last item matching the provided predicate.

Below is a complete example of how to search for elements in a dynamic array in C#.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> cities = new List<string>
        {
            "New York", "Los Angeles", "Dallas", "New Orleans", "Dallas", "Chicago"
        };

        // Using Contains
        Console.WriteLine(cities.Contains("Chicago"));  // True

        // Using IndexOf
        Console.WriteLine(cities.IndexOf("Dallas"));  // 2 (because Dallas first appears at index 2)

        // Using LastIndexOf
        Console.WriteLine(cities.LastIndexOf("Dallas"));  // 4

        // Using Find with a lambda expression
        string cityWithLetterO = cities.Find(city => city.Contains("o"));
        Console.WriteLine(cityWithLetterO);  // "Los Angeles" (first city containing the letter 'o')

        // Using FindAll with a lambda expression
        List<string> citiesWithLetterA = cities.FindAll(city => city.Contains("a"));
        foreach(string city in citiesWithLetterA)
        {
            Console.WriteLine(city);  // Displays all cities containing the letter 'a'
        }

        // Using FindIndex
        int index = cities.FindIndex(city => city.EndsWith("s"));
        Console.WriteLine(index);  // 1 (because "Los Angeles" is the first city ending with 's')
    }
}

  • Contains: The Contains method is a straightforward way to determine if a specific item exists in the list.
  • IndexOf and LastIndexOf: While IndexOf gives the position of the first occurrence of a specified item, LastIndexOf provides the position of its last appearance.
  • Find: This method can use a delegate, lambda, or anonymous method to define the search condition. It will return the first item that satisfies the given predicate.
  • FindAll: Similar to Find, but it returns all items that match the condition.
  • FindIndex and FindLastIndex: Both methods search for an item based on a predicate but return the index rather than the item itself.

Sorting and Reversing in a Dynamic Array in C#

Sometimes, you’ll need to organize data in a specific sequence, either for presentation, analysis or because an algorithm requires it. The List<T> class in C# offers efficient methods for sorting data in ascending order, and descending order, and reversing the order entirely.

Methods for Sorting and Reversing:

  1. Sort: Orders the elements in the entire List<T> or a portion of it.
  2. Reverse: Reverses the order of the elements in the entire list or a segment of it.

Here is a complete example of how to implement sorting and reversing in C# dynamic array.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> cities = new List<string>
        {
            "New York", "Los Angeles", "Dallas", "Chicago", "Atlanta"
        };

        // Default Sort
        cities.Sort();
        Console.WriteLine("Sorted Cities:");
        DisplayCities(cities);

        // Reverse the list
        cities.Reverse();
        Console.WriteLine("\nReversed Cities:");
        DisplayCities(cities);

        // Sort with a custom comparison (descending order)
        cities.Sort((city1, city2) => city2.CompareTo(city1));
        Console.WriteLine("\nSorted Cities in Descending Order:");
        DisplayCities(cities);
    }

    static void DisplayCities(List<string> citiesList)
    {
        foreach (var city in citiesList)
        {
            Console.WriteLine(city);
        }
    }
}
  • Sort: The Sort() method, by default, sorts the list in ascending order based on the natural order of the elements. For strings, this is alphabetical order, and for numbers, it’s numerical order. You can also pass a custom comparison delegate to the Sort method to customize the sorting, as shown in the descending order example.
  • Reverse: The Reverse() method, will invert the order of the elements in the list. If your list was [A, B, C], after applying Reverse, it would be [C, B, A].
  • Custom Sorting: By using a lambda expression, the Sort method can be customized to sort in descending order or by other criteria. In the provided example, the cities are sorted in descending order by reversing the arguments’ order in the CompareTo method.

Once you run the code, you can see the output below:

Sorted Cities:
Atlanta
Chicago
Dallas
Los Angeles
New York

Reversed Cities:
New York
Los Angeles
Dallas
Chicago
Atlanta

Sorted Cities in Descending Order:
New York
Los Angeles
Dallas
Chicago
Atlanta

See the screenshot below:

C# dynamic array with examples

Conclusion

Dynamic arrays, represented by the List<T> class in C#, offers a flexible way to handle collections of data without needing to define a fixed size up front. They come packed with methods that allow for easy manipulation of data, making them a preferred choice in many scenarios over traditional arrays. I hope you got a complete idea of the C# dynamic array with a few examples.

You may also like: