Skip to content

Instantly share code, notes, and snippets.

@grandsilence
Created March 6, 2020 03:45
Show Gist options
  • Save grandsilence/25c744f955db99ceab7827ec66d22b80 to your computer and use it in GitHub Desktop.
Save grandsilence/25c744f955db99ceab7827ec66d22b80 to your computer and use it in GitHub Desktop.
C# Deep Copy
public static T? DeepCopy<T>(this T self) where T : class
{
if (!typeof(T).IsSerializable)
throw new ArgumentException("Type must be serializable");
if (ReferenceEquals(self, null))
return default;
var formatter = new BinaryFormatter();
using var stream = new MemoryStream();
formatter.Serialize(stream, self);
stream.Seek(0, SeekOrigin.Begin);
return (T) formatter.Deserialize(stream);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment