|
Increasing an Array |
|
|
In most computer languages, including C++ and Pascal,
when creating an array, you must provide a fixed number of elements and you
cannot go over. Modern languages, such as C#, Java, Visual Basic, etc,
and libraries, such as the .NET Framework, also fully support arrays and
follow the orignal rules, but provide alternative solutions.
|
New libraries such as the .NET Framework allow you
to increase the size of an array when you judge it necessary. That is, when
declaring an array variable, you must provide a constant value as the number
of items but you can increase that number. To support this, the .NET Framework provides the
Array class that
is equipped with the Resize() method.
Still, at any time you judge it necessary, you can
increase the number of items. Instead of using the Array.Resize()
method, you can define your own method or function to perform this resizing
operation.
We provide an example here:
|
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Increase_Array
{
public class Routine
{
public static void IncreaseArray(ref string[] values, int increment)
{
string[] array = new string[values.Length + increment];
values.CopyTo(array, 0);
values = array;
}
}
public class Program
{
private static void Show(string[] ns)
{
foreach (string name in ns)
Console.WriteLine("Name: " + name);
}
static void Main(string[] args)
{
string[] names = new string[5];
Console.WriteLine("Length of names = " + names.Length.ToString());
Console.WriteLine("");
names[0] = "Alexander";
names[1] = "Paulette";
names[2] = "Gertrude";
names[3] = "Hélène";
names[4] = "Patricia";
Show(names);
Routine.IncreaseArray(ref names, 5);
Console.WriteLine("\nLength of names = " + names.Length.ToString());
Console.WriteLine("");
names[5] = "Alain";
names[6] = "Gerogette";
Show(names);
Console.WriteLine("");
}
}
}
This would produce:
Length of names = 5
Name: Alexander
Name: Paulette
Name: Gertrude
Name: Hélène
Name: Patricia
Length of names = 10
Name: Alexander
Name: Paulette
Name: Gertrude
Name: Hélène
Name: Patricia
Name: Alain
Name: Gerogette
Name:
Name:
Name:
Press any key to continue . . .
|
|