Created
March 6, 2020 03:45
-
-
Save grandsilence/25c744f955db99ceab7827ec66d22b80 to your computer and use it in GitHub Desktop.
C# Deep Copy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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