Expandable array

  • Thread starter Thread starter Simon Johnson
  • Start date Start date
S

Simon Johnson

In c# is it possible to resize an array cleanly?

My application is that I have a list of numbers i'd like to return from a
method as an integer array. I don't know before hand how many integers i'm
going to have.

Simon.
 
Hi

In this scenario I usually use an ArrayList to easily build the array. Once
finished, I use the ToArray method to get a real Array:

System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(3);
al.Add(5);
///...
return al.ToArray(typeof(int));

--
Greetz

Jan Tielens
________________________________
Read my weblog: http://weblogs.asp.net/jan
 
Good solution. You'll begin to take a boxing hit if the list becomes >50
items, since ArrayList stores as object type.

If its gonna be loading a lot of integers then I'd recommend building a
class for managing a int[] for efficiency reasons if this is gonna be a hard
hit area.

/me looks forward to C# generics ;-)
 
Eric

I agree, generics will be so cool in these scenarios...

--
Greetz,
Jan
__________________________________
Read my weblog: http://weblogs.asp.net/jan
Eric Newton said:
Good solution. You'll begin to take a boxing hit if the list becomes >50
items, since ArrayList stores as object type.

If its gonna be loading a lot of integers then I'd recommend building a
class for managing a int[] for efficiency reasons if this is gonna be a hard
hit area.

/me looks forward to C# generics ;-)

--
Eric Newton
C#/ASP Application Developer
http://ensoft-software.com/
(e-mail address removed)-software.com [remove the first "CC."]

Jan Tielens said:
Hi

In this scenario I usually use an ArrayList to easily build the array. Once
finished, I use the ToArray method to get a real Array:

System.Collections.ArrayList al = new System.Collections.ArrayList();
al.Add(3);
al.Add(5);
///...
return al.ToArray(typeof(int));

--
Greetz

Jan Tielens
________________________________
Read my weblog: http://weblogs.asp.net/jan
from
 
Eric Newton said:
Good solution. You'll begin to take a boxing hit if the list becomes >50
items, since ArrayList stores as object type.

If its gonna be loading a lot of integers then I'd recommend building a
class for managing a int[] for efficiency reasons if this is gonna be a hard
hit area.

/me looks forward to C# generics ;-)

While generics will indeed be very handy here, I certainly wouldn't
start writing my own type to deal with this kind of thing unless I'd
already determined that the boxing hit was actually causing a problem.
Premature optimisation is a bad idea, IMO.
 
Back
Top