ArrayList.AddRange()

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

I was wondering why it is that when adding a collection of controls to an
array list, you must use AddRange, instead of Add.

Thanks in advance for any ideas

Ant
 
Ant,

Well, if you are calling Add, you are adding the collection itself as
the single element to the arraylist. If you are calling AddRange, then you
are going to add all the elements of the collection individually to the
list.

Hope this helps.
 
Thanks that makes sense, however, if I add a collection of say, strings, or
an array of numbers, I can actually iterate through them as individual
elements, not so with a collection of controls. Why the difference?

Thanks for your thoughts.

Nicholas Paldino said:
Ant,

Well, if you are calling Add, you are adding the collection itself as
the single element to the arraylist. If you are calling AddRange, then you
are going to add all the elements of the collection individually to the
list.

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

Ant said:
Hi,

I was wondering why it is that when adding a collection of controls to an
array list, you must use AddRange, instead of Add.

Thanks in advance for any ideas

Ant
 
Ant said:
Thanks that makes sense, however, if I add a collection of say, strings, or
an array of numbers, I can actually iterate through them as individual
elements, not so with a collection of controls. Why the difference?

It's more descriptive (and simpler) in your code to call AddRange than
to iterate through.

The same can be said of many things - you could do without
String.Substring, using a StringBuilder to append each of the
characters you're interested in - but it would make life considerably
messier.
 
Jon said:
It's more descriptive (and simpler) in your code to call AddRange than
to iterate through.

In addition an AddRange() method often has better performance than
repeatedly calling an Add() method, as the class can often optimise its
access and manipulation of internal data structures (e.g. if it needs
to reallocate an array it can be done in one hit), and you're making
less method calls overall.


Matt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top