|
-
Jan 23rd, 2007, 02:30 AM
#1
Thread Starter
Addicted Member
[RESOLVED] [2.0] Dynamic array doubt?
Hi,
I have declared like this,
VB Code:
string[] a = new string[] {""};
a[0]="Senthil";
a[1] = "Kumar";
But this code does not allow to dynamically extend the array. it shows the error "Index was outside the bounds of the array" while executing the last statement. I need to know the array of string which is expandable at anywhere. Any help.
regards,
senthil.
God has been pleased to place as a king or cobbler do the work sincerely
-
Jan 23rd, 2007, 03:19 AM
#2
Re: [2.0] Dynamic array doubt?
Your first line specifically creates an array with one element that is an empty string. First of all, if that's not what you want then you shouldn't create it in the first place.
Arrays are not resizable. You can call the Array.Resize method but what that actually does is create a new array and copy all the elements. That is an expensive operation so should be done as infrequently as possible, particularly with large arrays. If you do need to use an array and resize it then it is best to enlarge it by more than one element each time. Alternatively you can use a collection, in your case a List<string>. A List<string> will internally maintain a string array and resize it as needed without you needing to explicitly do so. You just add and remove items as needed and the collection class will handle the resizing implicitly. It will normally start with a 16 element array and double the size each time the current capacity is insufficient. That means that the larger the array the less frequently it gets resized.
-
Jan 23rd, 2007, 07:42 AM
#3
Hyperactive Member
Re: [2.0] Dynamic array doubt?
For situations like that I like to use the ArrayList which as jmcilhinney said could be resized, you could add or delete elements easily.
Jen
-
Jan 24th, 2007, 03:00 PM
#4
Frenzied Member
Re: [2.0] Dynamic array doubt?
 Originally Posted by JenniferBabe
For situations like that I like to use the ArrayList which as jmcilhinney said could be resized, you could add or delete elements easily.
Jen
I would strongly recommend against using ArrayList in 2.0.
The expense alone of casting back and forth between (object) and the target data type warrants use of the strongly typed generic List<T>
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|