Sabari M Sabari M
Updated date Feb 18, 2021
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.
  • 3.3k
  • 0
  • 0

In C#, we have multiple ways to add elements to an array. In this blog, we will see how to add an element to an array using the Extension method and List<T> in C#. This extension method is a generic method so we can pass any array type to append the element.

Using this method, first, we will have to convert an array into the List, once converted then will append the new element to the end of the list. Finally, convert the list to an array and return.

In the below example, we will add the int type element to an 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();
        }
    }
}

Output:

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

In the below example, we will add the string type element to an 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();
	}
}

Output:

BMW,Ford,Audi,Toyota

 

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

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