How to convert ArrayList to generic counterpart?

  • Thread starter Thread starter hvj
  • Start date Start date
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
 
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
 
Back
Top