Gigi
Gigi

Reputation: 340

How to shallow copy of a list given as generic without knowing the items generic type parameter?

I got as far as:

T clone(T source)
{
    if(source != null && source.GetType() == typeof(List<>))
    {
        Type listType = source.GetType();
        Type listElemType = listType.GetGenericArguments()[0].GetType();
        var listClone = (T)Activator.CreateInstance(listType.MakeGenericType(listElemType));
        ...
        return listClone;
    }
    ...
}

Now, how to fill the clone? As I said, I just need a shallow copy. Thanks.

Upvotes: 1

Views: 396

Answers (1)

Turksarama
Turksarama

Reputation: 1136

I'm not sure why you would ever need this function. Presumably T is some kind of List<U> and you know this at compile time. In which case all you need is var listClone = myList.toList().

Upvotes: 0

Related Questions