1

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.

Gigi
  • 158
  • 11
  • 1
    If `T` is already `List`, you don't need to rebuild that type. But how is this method called? This is a bad code smell. If you are using generics, you should specify constraints so that you don't need to use reflection. – Jeremy Lakeman May 10 '21 at 00:57
  • If the types in the list are a reference type, do you want the same reference or a new reference? It's academic at best to clone a value type, it can be insanely hard to clone a reference type. – Erik Philips May 10 '21 at 04:21
  • @Erik Philips OP asked for [shallow copy](https://en.wikipedia.org/wiki/Object_copying#Shallow_copy). –  May 10 '21 at 04:29
  • 1
    @OlivierRogier You are aware of the technical definition of a shallow copy, I'm not sure the OP is. I probably should have just asked if he was aware of the technical term, otherwise a simple `ToList()` is all it takes. – Erik Philips May 10 '21 at 04:38
  • @ErikPhilips I don't think the duplicate can be used by the OP for the question asked. The OP made me discover the technical expression, thus the OP should be aware, especially since the OP insisted on this term. –  May 10 '21 at 04:58

1 Answers1

0

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().

Turksarama
  • 1,136
  • 6
  • 13