TechieClues TechieClues
Updated date Mar 11, 2024
In this blog, we will show you how to add new elements to an array in C#. We use the Extension method and List in C# to achieve this. This extension method is a generic method so we can pass any array type to append the element.
  • 35.1k
  • 0
  • 0

Introduction:

In C#, arrays are widely used data structures for storing collections of elements. However, arrays have a fixed size, which means you cannot directly add elements to them once they are created. To overcome this limitation, we can use extension methods in combination with the List<T> class to add elements dynamically to an array. This blog explores how to achieve this functionality through code examples in C#.

Method 1: Adding an integer element to an integer array

we have a static class named ExtensionClass, which contains an extension method named Append<T>. This method takes two parameters: the first parameter is the array to which we want to add an element, and the second parameter is the element itself that we want to append.

The extension method Append<T> begins by creating a new List<T> instance and initializing it with the elements of the input array. This conversion allows us to use the List<T> methods, including the Add method, to add the new element to the list. Once the element is appended to the list, the method converts the list back to an array using the ToArray() method and returns the updated array.

namespace ConsoleApp
{
    public static class ExtensionClass
    {
        // Extension method to append the element
        public static T[] Append<T>(this T[] array, T item)
        {
            List<T> list = new List<T>(array);
            list.Add(item);

            return list.ToArray();
        }
    }

    public class AddElementToArray
    {
        public static void Main()
        {
            // Declaration
            int[] array = { 1, 2, 3, 4, 5, 6, 7, 9, 9, 10 };
            // Item to be added
            int addItem = 11;

            // Append Item
            int[] result = array.Append(addItem);

            // Print elements
            Console.WriteLine(String.Join(",", result));

            Console.ReadKey();
        }
    }
}

In the above code, we have an integer array named array with some initial values. We want to add a new integer value, addItem, to this array using the Append method. After invoking the Append method, the result array will hold the original elements of array along with the newly added integer.

Output:

1,2,3,4,5,6,7,9,9,10,11

Method 2: Adding a string element to a string array

public class AddElementToArray
{
	public static void Main()
	{
		// Declaration
		string[] cars = { "BMW", "Ford", "Audi" };
		// Item to be added
		string addCar = "Toyota";

		// Append Item
		string[] result = cars.Append(addCar);

		// Print elements
		Console.WriteLine(String.Join(",", result));

		Console.ReadKey();
	}
}

In the above code, we have a string array named cars containing a list of car brands. We wish to add a new car brand, addCar, to this array using the Append method. After the Append operation, the result array will contain all the original car brands along with the new one.

Output:

BMW,Ford,Audi,Toyota

Conclusion:

In this blog, we explored a useful approach for adding elements to arrays in C# using extension methods and the List<T> class. This technique allows us to overcome the fixed-size limitation of arrays and dynamically extend their contents with new elements. By leveraging the extension method Append<T>, we can easily add elements to various types of arrays, making our code more flexible and efficient.

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!