Skip to content

Instantly share code, notes, and snippets.

@CapitanLiteral
Created February 10, 2020 13:36
Show Gist options
  • Save CapitanLiteral/9aee0a552ab57bd205e4938246b38906 to your computer and use it in GitHub Desktop.
Save CapitanLiteral/9aee0a552ab57bd205e4938246b38906 to your computer and use it in GitHub Desktop.
public static class BinaryFormatterWrapper
{
private static BinaryFormatter BinaryFormatter => binaryFormatter ?? (binaryFormatter = new BinaryFormatter());
private static BinaryFormatter binaryFormatter;
public static byte[] SerializeToByteArray(this object obj)
{
using (MemoryStream memoryStream = new MemoryStream())
{
BinaryFormatter.Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
public static T DeserializeFromByteArray<T>(this byte[] byteArray) where T : class
{
using (MemoryStream memoryStream = new MemoryStream())
{
memoryStream.Write(byteArray, 0, byteArray.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
T obj = (T)BinaryFormatter.Deserialize(memoryStream);
return obj;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment