Friday, November 20, 2009

C# Dynamic array

Sample code to test a dynamic array in C#
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
DynamicArray da = new DynamicArray();
for (int i = 0; i < 60; i++)
{
da.AddObject(i);
}
da.readArray();
Console.ReadLine();
}
}
class DynamicArray
{
private object [] _objArray ;
private const int ARRAY_INITIAL_SIZE = 10;
private const int NEXT_INCREMENT_SIZE = 10;
private int _currentIndex = 0;
public DynamicArray()
{
_objArray = new object[ARRAY_INITIAL_SIZE];
}
public void AddObject(object o)
{
if (_currentIndex < _objArray.Length)
{
_objArray[_currentIndex] = o;
_currentIndex++;
}
else
{
growArray();
_objArray[_currentIndex] = 0;
_currentIndex++;
}
}
void growArray()
{
object[] tempArray = new object[_objArray.Length + NEXT_INCREMENT_SIZE];
_objArray.CopyTo (tempArray ,0);
_objArray = tempArray;
}
public void readArray()
{
for (int i = 0; i < _objArray.Length ; i++)
{
Console.WriteLine(i.ToString());
}
}
}
}

No comments: