In this article, i’ll 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.
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,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
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, 8, 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 |
1,2,3,4,5,6,7,8,9,10,11 |
In the below example, we will add the string
type element to an array,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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
1 2 3 |
BMW,Ford,Audi,Toyota |