Reducing the size of an Array
-
If i create an array that is a specific size
int[] myInts = new int[10]
but only fill the first 5 values, how can i reduce the length of the array to 5? so the following will happen
myInts[0] = 5;
myInts[1] = 4;
myInts[2] = 3;
myInts[3] = 2;
myInts[4] = 1;
for (int i = 0; i < myInts.Length; i++)
{
Console.WriteLine(myInts[i].ToString());
}and the output would only be 5, 4, 3, 2, 1 and not throw an exception since myInts[5] is null
-
If i create an array that is a specific size
int[] myInts = new int[10]
but only fill the first 5 values, how can i reduce the length of the array to 5? so the following will happen
myInts[0] = 5;
myInts[1] = 4;
myInts[2] = 3;
myInts[3] = 2;
myInts[4] = 1;
for (int i = 0; i < myInts.Length; i++)
{
Console.WriteLine(myInts[i].ToString());
}and the output would only be 5, 4, 3, 2, 1 and not throw an exception since myInts[5] is null
hi, if the size of the array is unknown before it is used then you must check each member of the array for null value. Change tour for loop to this for( int i = 0; i < nyInts.Length, myInts[i] != null; i ++ ) as i know there is no any function to resize of an array. cheers, Doing something is better than doing nothing. So ... Move !
-
If i create an array that is a specific size
int[] myInts = new int[10]
but only fill the first 5 values, how can i reduce the length of the array to 5? so the following will happen
myInts[0] = 5;
myInts[1] = 4;
myInts[2] = 3;
myInts[3] = 2;
myInts[4] = 1;
for (int i = 0; i < myInts.Length; i++)
{
Console.WriteLine(myInts[i].ToString());
}and the output would only be 5, 4, 3, 2, 1 and not throw an exception since myInts[5] is null
If you need to resize an array, you should go throug the ArrayList, even though it isn't typed. If you need a typed array, but don't know the size of it you can use ArrayList in this way:
ArrayList al = new ArrayList(); al.add(5); al.add(4); al.add(3); al.add(2); al.add(1); int[] myInts = (int[])al.ToArray(typeof(int));
If you need to change the size of the array, you can start withArrayList al = new ArrayList(myInts);
instead. This will add some overhead (going back and forth between arrays and arraylists), but it gives you the type safety you need.