Skip to content

Instantly share code, notes, and snippets.

@cyptus
Created March 6, 2019 10:19
Show Gist options
  • Save cyptus/20e02d2cda99bc5752fc16a0677691d2 to your computer and use it in GitHub Desktop.
Save cyptus/20e02d2cda99bc5752fc16a0677691d2 to your computer and use it in GitHub Desktop.
public class BinaryConverter
{
public static BinaryConverter Instance => new BinaryConverter();
public byte[] ToBinary<T>(T message) where T : class, new()
{
var bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
ms.Position = 0;
bf.Serialize(ms, message);
return ms.GetBuffer();
}
}
public T FromBinary<T>(byte[] data) where T : class, new()
{
using (var ms = new MemoryStream(data))
{
ms.Position = 0;
var bf = new BinaryFormatter();
return bf.Deserialize(ms) as T;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment