# Cloning Object
###### tags: `C#`
[reference](https://www.infoworld.com/article/3109870/my-two-cents-on-deep-copy-vs-shallow-copy-in-net.html)
## Shallow copy
Methods:
* assign `=`
* `MemberwiseClone()`
A new object is created and then the non-static members of the source object is copied to the target object or the new object.
:arrow_right: If the member is a `value type field` : a bit by bit copy of the field is performed.
:arrow_right: If the member is a `reference type`: the reference is copied. Hence, the reference member inside the original object and the target objects refer to the same object in the memory.
:::success
### [Value type vs Reference type](https://www.tutorialsteacher.com/csharp/csharp-value-type-and-reference-type)
`value type`: A data type is a value type if it holds a data value within its own memory space.
=> bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort
`reference type`: stores the address where the value is being stored.
=> String, All arrays (even if their elements are value types), Class, Delegates
:::
## Deep Copy
Methods:
* serialization
* DIY :laughing:
```csharp=
public static T DeepCopy<T>(T other)
{
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, other);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
```