Dynamic Arrays

This post is more for my benefit, as I always seem to forget the way it is done.  I was needing to create a dynamic array in C#, was using the int[] type, but I started to see that it was a fix size.  Having come from Visual Basic, which supports them out of the box.

Dim myArray() as Integer

For i as Integer = 0 to 100
	ReDim Preserve myArray(i)
	myArray(i) = i
Next

The code above shows this, it is straight forward and no fuss.  So I started coding it the same way only to find that it was perhaps not the way I thought.

C# (and Visual Basic since it is part of the .NET Framework) has the ArrayList.  This class works very much like a List class, in fact it implement the IList interface.  But it still operates like an array.

ArrayList tempArray = new ArrayList();

for (int i == 0; i <= 100; i++)
{
	tempArray.Add(i);
}

Seems very much like the list code, but the difference with this is, though it does support the IEnumerable and can be used with the For Each mechanism, it can also be used like an array.

tempArray[0] = 30;

This shows that I can overwrite the value in the first element with a new value.  Like a normal array.

Technorati Tags: ,,,
Advertisements

Posted on March 26, 2013, in Tips and Tricks and tagged . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: