When I do the following.. anything done to Person b modifies Person a (I thought doing this would clone Person b from Person a). I also have NO idea if changing Person a wil
Painlessly: Using NClone library
Person a = new Person() { head = "big", feet = "small" };
Person b = Clone.ObjectGraph(a);
It couldn't be simpler than this:
public SomeClass Clone () {
var clonedJson = JsonConvert.SerializeObject (this);
return JsonConvert.DeserializeObject<SomeClass> (clonedJson);
}
Just serialize any object to a JSON string and then deserialize it. This will do a deep copy...
You could do it like this:
var jss = new JavaScriptSerializer();
var b = jss.Deserialize<Person>(jss.Serialize(a));
For deep cloning you may want to take a look at this answer: https://stackoverflow.com/a/78612/550975
a
and b
are just two references to the same Person object. They both essentially hold the address of the Person
.
There is a ICloneable interface, though relatively few classes support it. With this, you would write:
Person b = a.Clone();
Then, b would be an entirely separate Person
.
You could also implement a copy constructor:
public Person(Person src)
{
// ...
}
There is no built-in way to copy all the fields. You can do it through reflection, but there would be a performance penalty.
This happens because "Person" is a class, so it is passed by reference. In the statement "b = a" you are just copying a reference to the one and only "Person" instance that you created with the keyword new.
The easiest way to have the behavior that you are looking for is to use a "value type".
Just change the Person declaration from
class Person
to
struct Person
Since the MemberwiseClone() method is not public, I created this simple extension method in order to make it easier to clone objects:
public static T Clone<T>(this T obj)
{
var inst = obj.GetType().GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
return (T)inst?.Invoke(obj, null);
}
Usage:
var clone = myObject.Clone();