Home All Groups Group Topic Archive Search About

How to convert ArrayList to generic counterpart?

Author
6 Nov 2007 2:06 PM
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

Author
6 Nov 2007 2:32 PM
Jon Skeet [C# MVP]
On Nov 6, 2:06 pm, h***@paralax.nl wrote:
> 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

AddThis Social Bookmark Button