Reputation:
How can I add a single Integer to an Integer Array?
if (valuesHigherThanAverage.Length == 0) valuesHigherThanAverage[valuesHigherThanAverage.Length] = arrayGetal;
else valuesHigherThanAverage[valuesHigherThanAverage.Length + 1] = arrayGetal;
I have this code and I have also tried with for or foreach loop but it doesn't worked. And I need to use an INT[] and may not use an List.
Upvotes: 0
Views: 7201
Reputation: 686
You can create a new Array with the length of the old array + 1.
public static int[] AddIntToArray(int[] sourceArray, int addValue)
{
int[] newArray = new int[sourceArray.Length + 1];
Array.Copy(sourceArray, newArray, sourceArray.Length);
newArray[newArray.Length] = addValue;
return newArray;
}
Upvotes: 0
Reputation: 3365
The array is not designed to be extended as new elements are added. You will need to call Array.Resize(Of T)
to increase the size but this is will be quite inefficient.
Data types more in line for what you want to do is List<T>
.
Upvotes: 0
Reputation: 157116
You can't add a new item in an array, you have to create a new array with size+1, copy all existing values, and then set the last item value.
An easier way is to use a List<int>
, which will automatically resize if you run out of space. Calling the Add
method suffices then.
Here a sample of an array resizing algorithm (Array.Resize
could automate this, but this is just to show you how it should work):
int[] oldItems = new int[] { 1, 2, 3 };
int[] newItems = new int[oldItems.Length * 2];
for (int i = 0; i < oldItems.Length; i++)
{
newItems[i] = oldItems[i];
}
newItems[oldItems.Length + 1] = 4;
Upvotes: 3
Reputation: 447
You cannot change the size of array like valuesHigherThanAverage.Length + 1
. It has fixed size. You are crossing the upper bound of the array.
Upvotes: 0