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
Comments (0)