I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do list.Clone()
.
Is there an easy way around this?
I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do list.Clone()
.
Is there an easy way around this?
If you only care about value types...
And you know the type:
If you don't know the type before, you'll need a helper function:
The just:
You can use an extension method.
If your elements are value types, then you can just do:
However, if they are reference types and you want a deep copy (assuming your elements properly implement
ICloneable
), you could do something like this:Obviously, replace
ICloneable
in the above generics and cast with whatever your element type is that implementsICloneable
.If your element type doesn't support
ICloneable
but does have a copy-constructor, you could do this instead:Personally, I would avoid
ICloneable
because of the need to guarantee a deep copy of all members. Instead, I'd suggest the copy-constructor or a factory method likeYourType.CopyFrom(YourType itemToCopy)
that returns a new instance ofYourType
.Any of these options could be wrapped by a method (extension or otherwise).
After a slight modification you can also clone:
Use AutoMapper (or whatever mapping lib you prefer) to clone is simple and a lot maintainable.
Define your mapping:
Do the magic: