.comment-link {margin-left:.6em;}
My Photo
Name:
Location: Unspecified, Mauritius

I too, am a bug within Māyā.

My Other Blog(s) and Site(s)
Friend sites and blogs
My Recent Posts
Tutorials
Best Articles
My C-Sharp Ideas
Archives
Blog Directories

Tuesday, September 26, 2006

 

Increase Array Bounds in C#

It's been a long time since I posted anything useful on this blog. I recently looked up the list of things people were looking for before falling onto this blog.

Increase Array Bounds in C#
For those of you who are new to C#, let me quickly sum this up: don't use arrays unless you're absolutely and positively certain that the array you're using will never use more than the number of values you created it for. Use an array for the number of days. Use an array of 8 bits to hold a byte. Use an array of 12 for the number of months. Those are values that we're absolutely sure will never change.

If you ever need to increase the size of an array somewhere in your code - you had it wrong. Use the ArrayList from the System.Collection namespace, or List System.Collections.Generic if you're on .Net 2.0 to create and use dynamic arrays.

Here's some sample code for you to have fun with:


//create an arraylist to hold some values
ArrayList myList = new ArrayList();

//add a few values to the arraylist
myList.Add(10);
myList.Add(11);
myList.Add(8);

//value to hold the sum of the values
int sum = 0;

//sum the values in the arraylist
foreach (int i in myList)
{
sum += i;
}

//display the sum
Console.WriteLine(sum.ToString());