Binary Serializer

Other Serialization technologies include XML and JSON Serialization.

System.Runtime.Serialization.Formatters.Binary

The stream should be wrapped in a using statement for production ready code.

1
2
3
4
5
var stream = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(stream, someObject);
stream.Seek(0, SeekOrigin.Begin); // Rewind the stream with offset of 0 from the begining
stream.Close();

Caveat

The object being serialized needs to have the [Serializable] attribute / annotation.

1
2
3
4
5
6
7
[Serializable]
public class Person
{
public string FirstName;
public Address Address;

...

References