ToArray() ?

  • Thread starter Thread starter Peter Kirk
  • Start date Start date
P

Peter Kirk

Hi

I call a method which returns an IList containing a list of one type of
object. How do I best convert this IList to an array?

I can see that the ArrayList class has a ToArray() method - but this is not
part of IList.

(I do in fact know that the method I call actually returns an ArrayList as I
have looked in the source code, but technically I really only know it is an
IList).

Thanks,
Peter
 
I call a method which returns an IList containing a list of one type of
object. How do I best convert this IList to an array?

IList list = ...
Foo[] foos = new Foo[list.Count];
for ( int i = 0; i < foos.Length; i++ )
foos = (Foo)list;



Mattias
 
Mattias Sjögren said:
I call a method which returns an IList containing a list of one type of
object. How do I best convert this IList to an array?

IList list = ...
Foo[] foos = new Foo[list.Count];
for ( int i = 0; i < foos.Length; i++ )
foos = (Foo)list;


Well, yeah. I just thought there might be an "in bult" method a la
ArrayList's ToArray().

Thanks,
Peter
 
How about using ICollection.CopyTo(...). IList implements ICollection.


Peter Kirk said:
Mattias Sjögren said:
I call a method which returns an IList containing a list of one type of
object. How do I best convert this IList to an array?

IList list = ...
Foo[] foos = new Foo[list.Count];
for ( int i = 0; i < foos.Length; i++ )
foos = (Foo)list;


Well, yeah. I just thought there might be an "in bult" method a la
ArrayList's ToArray().

Thanks,
Peter
 
Peter Kirk said:
Hi

I call a method which returns an IList containing a list of one type of
object. How do I best convert this IList to an array?

You can load it into an ArrayList and uses ArrayLists.ToArray() if you
aren't worried about performance, otherwise I'd recommend writing a ToArray
implemetnation that takes an IList. Its not terribly hard to do, especially
if you know the type the list is going to be at all times.
 
Back
Top