0
0
CsharpHow-ToBeginner · 4 min read

How to Use Binary Serialization in C# - Simple Guide

In C#, use the BinaryFormatter class to serialize objects to a binary format and deserialize them back. Mark your class with [Serializable] attribute, then use Serialize() and Deserialize() methods with a FileStream or MemoryStream.
📐

Syntax

Binary serialization in C# uses the BinaryFormatter class to convert objects into a binary stream and back. Your class must be marked with the [Serializable] attribute to allow serialization.

  • BinaryFormatter.Serialize(Stream, object): Saves the object to a stream in binary form.
  • BinaryFormatter.Deserialize(Stream): Reads the binary stream and reconstructs the object.
  • FileStream or MemoryStream is used to hold the binary data.
csharp
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class MyClass
{
    public int Number;
    public string Text;
}

// To serialize:
MyClass myObject = new MyClass { Number = 1, Text = "Example" };
BinaryFormatter formatter = new BinaryFormatter();
using (FileStream stream = new FileStream("data.bin", FileMode.Create))
{
    formatter.Serialize(stream, myObject);
}

// To deserialize:
using (FileStream stream = new FileStream("data.bin", FileMode.Open))
{
    MyClass obj = (MyClass)formatter.Deserialize(stream);
}
💻

Example

This example shows how to save an object to a binary file and then read it back, restoring the original data.

csharp
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Person
{
    public string Name;
    public int Age;
}

class Program
{
    static void Main()
    {
        Person person = new Person { Name = "Alice", Age = 30 };
        BinaryFormatter formatter = new BinaryFormatter();

        // Serialize to file
        using (FileStream stream = new FileStream("person.bin", FileMode.Create))
        {
            formatter.Serialize(stream, person);
        }

        // Deserialize from file
        using (FileStream stream = new FileStream("person.bin", FileMode.Open))
        {
            Person loadedPerson = (Person)formatter.Deserialize(stream);
            Console.WriteLine($"Name: {loadedPerson.Name}, Age: {loadedPerson.Age}");
        }
    }
}
Output
Name: Alice, Age: 30
⚠️

Common Pitfalls

  • Not marking the class with [Serializable] causes runtime errors.
  • BinaryFormatter is not secure for untrusted data; avoid deserializing data from unknown sources.
  • Fields marked with [NonSerialized] will not be saved.
  • Versioning changes in classes can break deserialization.
csharp
/* Wrong: Missing [Serializable] attribute */
public class Data
{
    public int Value;
}

// This will throw an exception when serializing.

/* Right: Add [Serializable] */
[Serializable]
public class Data
{
    public int Value;
}
📊

Quick Reference

Remember these key points when using binary serialization in C#:

  • Use [Serializable] on classes to enable serialization.
  • Use BinaryFormatter with streams to serialize/deserialize.
  • Avoid using BinaryFormatter with untrusted data for security reasons.
  • Use [NonSerialized] to exclude fields from serialization.

Key Takeaways

Mark classes with [Serializable] to enable binary serialization.
Use BinaryFormatter with streams to save and load objects in binary form.
Avoid deserializing untrusted data with BinaryFormatter due to security risks.
Use [NonSerialized] to skip fields during serialization.
Binary serialization preserves object state but can break if class structure changes.