Serialization in C#: Persistently Storing Object Data

Learn about serialization in C#, the process of converting objects into byte streams for persistent storage. This tutorial explains the `[Serializable]` attribute, demonstrates serialization using `BinaryFormatter`, and covers deserialization, enabling you to save and restore object states in your C# applications.



Serialization in C#

Serialization in C# is the process of converting an object into a stream of bytes. This allows you to store the object's state (its data) persistently, such as in a file or database. Deserialization is the reverse process—reconstructing the object from the byte stream.

The `SerializableAttribute`

To serialize an object in C#, you must mark the class or struct with the `[Serializable]` attribute. If you don't, a `SerializationException` is thrown at runtime.


[Serializable]
public class MyClass {
    // ... class members ...
}

Example: Serializing a Student Object

This example serializes a `Student` object using the `BinaryFormatter` class. This creates a binary representation of the object's data.


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

// ... ([Serializable] Student class definition) ...

public class SerializationExample {
    public static void Main(string[] args) {
        FileStream stream = new FileStream("data.bin", FileMode.Create);
        BinaryFormatter formatter = new BinaryFormatter();
        Student student = new Student(101, "Alice");
        formatter.Serialize(stream, student);
        stream.Close();
    }
}

(Note: The `sss.txt` file content shown in the original text is the result of serializing the object; this will vary based on the system.)