How to convert ArrayList to generic counterpart?

H

hvj

Hi,

I want to be able to convert an ArrayList containing objects of one
type to a generic of a specified type, like

List<T> ConvertArrayListToGeneric(ArrayList list, System.Type
targetType)

How do I do that?

What I am doing now is to write a separate conversion method for every
target type but with generics I don't think this should be necessary.

Any help appreciated
 
J

Jon Skeet [C# MVP]

I want to be able to convert an ArrayList containing objects of one
type to a generic of a specified type, like

List<T> ConvertArrayListToGeneric(ArrayList list, System.Type
targetType)

How do I do that?

What I am doing now is to write a separate conversion method for every
target type but with generics I don't think this should be necessary.

Use a generic method instead:

List<T> ConvertToList<T>(ArrayList list)
{
List<T> ret = new List<T>();
foreach (T item in list)
{
ret.Add(item);
}
return ret;
}

Jon
 

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

Top