Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Binary Serialization in C#

Introduction

Binary Serialization is a process of converting an object into a binary format that can be stored or transmitted and then reconstructed later. In C#, this is commonly used for saving the state of an object or for sending objects over a network. This tutorial will guide you through the steps necessary to perform binary serialization in C#.

Requirements

Before we start, ensure you have the following:

  • Basic understanding of C# programming.
  • Visual Studio or any other C# IDE installed.
  • .NET Framework.

Step 1: Define a Serializable Class

First, we need to define a class that we want to serialize. This class should be marked with the [Serializable] attribute.


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

In this example, the Person class has two properties: Name and Age.

Step 2: Serialize the Object

To serialize an object to a binary format, we use the BinaryFormatter class. Here is an example:


Person person = new Person { Name = "John Doe", Age = 30 };
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("person.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, person);
stream.Close();
                

This code creates a new Person object and serializes it to a file named person.bin.

Step 3: Deserialize the Object

To deserialize the object, we read the binary data from the file and convert it back to a Person object:


Stream stream = new FileStream("person.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
IFormatter formatter = new BinaryFormatter();
Person person = (Person)formatter.Deserialize(stream);
stream.Close();
                

After deserialization, you can use the person object as needed:


Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
                
Name: John Doe, Age: 30

Conclusion

Binary serialization in C# is a powerful feature that allows you to save and restore the state of your objects easily. It is particularly useful for persisting data to files or for network communication. By following the steps outlined in this tutorial, you should be able to implement binary serialization in your own C# projects.