There's something out there in life that will delight and amaze you.
Get up, get moving, and go find out what it is. - (Ralph Marston)

Friday, April 25, 2008

Solution to Dynamic Length Arrays in C#

Creating dynamic length arrays is often a requirement, but arrays do have a limitation in this point. C# allows you to create dynamic length arrays as follows.

int[] intAry = new int[] { 1, 2, 3 };

If your requirement is simple as this, then fine. But what if you want to create an array based on the elements you add and specify the length accordingly.

You could use : Array.Resize<int>(ref intAry, 2);  to resize. But again you may have to traverse through the array or use another array to copy the elements.

Arrays do have a limitation where you cannot make it grow dynamically. Collections on the other hand grows dynamically. Here's a solution to the dynamic length arrays.

List<int> oNumList = new List<int>(); //Haven't specified the size

oNumList.Add(1123); //Add items to the list

int[] oNums = new int[oNumList.Count]; //Create an int Array

oNums = oNumList.ToArray(); //Convert the List to an Array

C# List<> allows you to create a List<T> specifying the type in T. So, create a List<int> of type int and add the items to it, with out specifying the count of the List. Then convert it back to an Array. There could be other solutions to this as well..

1 Comments:

At 1:02 PM, Anonymous Muneer said...

Simple short and sweet,,
Great!!

 

Post a Comment

<< Home