Could anyone please explain how to use Arraylists? And is this really the only way to store info dynamically? if so I think I'll miss malloc. The reason I need to allocate memory dynamically is I'm trying to make a program which asks the user for any number of integers. At first they are stored in a string using "string input = Console.Readline()", after that I use a for-loop to detect the actual integers and try sorting out other letters and spaces that the user could have entered by mistake. This is the point where I need to store the integers dynamically while converting them from the string. And I know about the split() method but I think it's good to practice myself.
I would really appreciate all suggestions and help I can get!
As far as I know there is no other way to have a dynamic array in C#, unless you do something like
- create normal 1d array of ints
- check wether last value of the array is not null
copy complete array into a bigger array
do some garbage collection
continue adding values
The only major problem with an ArrayList is the boxing of the ints to objects, and when reading and converting to ints from the arraylist the unboxing.
You can easily test performance of an ArrayList vs a normal array by timing the operation like this
start timer for arraylist
store a bunch of ints or whatever in the arraylist
retrieve them again from the arraylist
stop timer for arraylist
now do the same for a normal array and see the difference, most of the time needed to add / retrieve values from an ArrayList goes into the boxing/unboxing...
edit: a quick solution to your problem is to do something like
But as you can see ... its somehow messy...
string input = Console.ReadLine();
//go over string and check how many ints there are -> store result in "numberOfInts"
ar = new int[numberOfInts];
//go again over the whole string and add ints to the array
If you're using the 2.0 framework, you can use a generic List instead of the ArrayList. The generic List doesn't suffer the same performance penalties as the ArrayList with boxing/unboxing. Further, all access of the generic List is strongly typed, not object references that you have to cast every time.
Thanks for your replies, I choose GanglyLambs technique with the 2 loops, and it works fine.
Well if you are using framework 2.0 I would go for the approach that pianorain suggested.
Didnt even know myself about these Generic Lists ( but now I do :) ), I looked into it briefly and it would be far better then using the dirty way with the two loops... ( that is if you are writing for the 2.0 ).
But then again you are just doing this as an exercise to implement your own split method , using "dynamic" arrays , so I it really doesnt matter anyway ...