Add New Item In Array In C#
Code snippet for how to Add New Item In Array In C# with sample and detail explanation
Manipulating arrays in C# is an essential skill for any developer working with this language. This article is a simple step-by-step guide on how to add a new item to a pre-existing array in C#.
Code snippet to Add a New Item in Array In C#
using System;
public class Program
{
public static void Main()
{
int[] arr = new int[4]{1,2,3,4};
int[] newArr = new int[arr.Length + 1];
arr.CopyTo(newArr, 0);
newArr[newArr.Length - 1] = 5;
foreach (var item in newArr)
{
Console.WriteLine(item);
}
}
}
Code Explanation for Add a New Item in Array In C#
Step 1: Beginning with the public static void Main()
function, which is the entry point for our program.
Step 2: We created an integer array named ”arr
” of size 4 and initialized it with the elements 1, 2, 3, and 4.
int[] arr = new int[4]{1,2,3,4};
Step 3: We then created a new integer array named ”newArr
”. Notice that the length is arr.Length+1, this is because we want to add a new item into the new Array then copied the contents of the first array into the second array using the CopyTo()
method.
int[] newArr = new int[arr.Length + 1];
arr.CopyTo(newArr, 0);
Step 4: We added the new item to the new array ”newArr
” by setting the last position (which is newArr[newArr.Length - 1]) with the new element value 5.
newArr[newArr.Length - 1] = 5;
Step 5: We then outputted the elements of the new array using a foreach
loop.
foreach (var item in newArr)
{
Console.WriteLine(item);
}
When you run this program, it will output the numbers 1 to 5 representing the items in the newArr
array. This is because we started with an array of integers from 1 to 4, and then added a new item, 5, specifically to this array using the steps and code detailed above.