The notion like "copy a class" makes no sense. You can copy the instance of the class, object, not a class itself. What you need is also called cloning
The simplest way to clone and object is to call object.MemberwiseClone
on your instance. Note that is will create a shallow copy
of the object. This is not a problem for your string members, because strings, being reference objects, mimic value semantics and use intern pool
, but your collection, being shallow copies, will create a dependency between source object and its copy: when, for example, you add elements in one collection, it will add them in the collection of a copy, because they share the same collection object, keeping two different references to the same object.
To create independent collection members, you would need to clone it: create a brand new one and copy elements independently. Would it be a full deep copy
of original object? It depend on the element type of the collection. If
is a reference type, the elements will be shared. If you want to have deep clones in all cases, you would need to solve a more difficult problem: create an universal mechanism of deep cloning. For example, you could create an interface for deep cloning, but then you would need to require all classes participating in your object graph
to support it; besides, you would need to implement this interface in all participating classes. In other words, it would be a considerable work, something to think at and design thoroughly.