c# add values to end of array code example

Example 1: c# add element to array

private T[] AddElementToArray<T>(T[] array, T element) {
    T[] newArray = new T[array.Length + 1];
    int i;
    for (i = 0; i < array.Length; i++) {
        newArray[i] = array[i];
    }
    newArray[i] = element;
    return newArray;
}

Example 2: how to append an element to an array in c#

//1. declare the array with a specified length:
int[] MyArray= new int[10];
for (int i=0; i<11; i++){
  //here i insert the elements
  MyArray[i]= i*2;
}
/*attention! in this way you are only putting in values in the array, you
are not modifying the length of the array, if you try to add more elements
than the length of the array it will throw a range out of index exeption*/

//2. you can also use a variable to define how long the array is:
//in this way you can have a different array length avery time you run the program
string Input= Console.ReadLine();
int[] MyArray= new int[Input.Length()];
for (int i=0; i<input.Length(); i++){
  //here i insert the elements
  MyArray[i]= i+1;
}

/*concluding the syntax is:
name of the array[index where you want to assign the value]= value you want to assign;
*/