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..

3 Comments:

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

Simple short and sweet,,
Great!!

 
At 1:44 PM, Anonymous simi said...

hi,

First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

There is a good C# resource site, Have alook

http://www.csharptalk.com/2009/09/c-array.html
http://www.csharptalk.com/2009/10/creating-arrays.html

simi

 
At 1:45 PM, Anonymous simi said...

hi,

First of all. Thanks very much for your useful post.

I just came across your blog and wanted to drop you a note telling you how impressed I was with the information you have posted here.

Please let me introduce you some info related to this post and I hope that it is useful for .Net community.

There is a good C# resource site, Have alook

http://www.csharptalk.com/2009/09/c-array.html
http://www.csharptalk.com/2009/10/creating-arrays.html

simi

 

Post a Comment

<< Home