Understanding .NET Binary Serialization

What is Serialization?

Serialization is the process of converting an object into a stream of bytes, which can be stored or transmitted. This stream of bytes can then be deserialized back into an object. Serialization is crucial for various tasks, such as:

  1. Storing objects: Saving objects to disk or database.
  2. Transmitting objects: Sending objects over a network.
  3. Passing objects between application domains: Sharing objects between different parts of an application.

What is Binary Serialization?

Binary serialization is a process that converts complex objects into a linear sequence of bytes. This serialized data can be stored or transmitted and later deserialized to restore the original object's structure and state.

Why Use Binary Serialization?

  1. Efficiency: Binary serialization produces compact representations of data, leading to smaller file sizes and faster data transfer.
  2. Performance: Deserializing binary data is significantly faster than text-based formats, optimizing application performance.
  3. Interoperability: Binary serialized data can be readily parsed and interpreted across various programming languages and platforms, promoting data exchange and compatibility.

How to use Binary Serialization?

Let me explain with an example.

Step 1. Create a class named Customer and mark the class as [Serializable].

[Serializable]
public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

The [Serializable] attribute marks the class as serializable.

Step 2. Create a generic interface named ITransform<T>.

public interface ITransform<T>
{
    public void Serialize(T obj, string filePath);
    public T Deserialize(string filePath);
}

It contains two abstract methods.

  1. Serialize: Accepts a generic object and a string as input.
  2. Deserialize: Accepts a string as input.

Step 3. Extend & implement the ITransform<T> interface.

public class BinarySerializer<T>: ITransform<T> where T: class
{
    public void Serialize(T obj, string filePath)
    {
        using var stream = new FileStream(filePath, FileMode.Create);
        
        var formatter = new BinaryFormatter();
        formatter.Serialize(stream, obj);
        
    }
    public T Deserialize(string filePath)
    {
        using var stream = new FileStream(filePath, FileMode.Open);
        
        var formatter = new BinaryFormatter();
        return (T)formatter.Deserialize(stream);
        
    }
}

Code explanation

void Serialize(T obj, string filePath)

  1. T obj: This is a generic parameter T representing the object to be serialized. This means the method can serialize any object type that is compatible with the BinaryFormatter.
  2. string filePath: This is the path to the file where the serialized data will be stored.
  3. using var stream = new FileStream(filePath, FileMode.Create)
    • This line creates a new FileStream object named stream.
    • The filePath parameter specifies the path to the file where the serialized data will be written.
    • The FileMode.Create flag ensures that a new file is created at the specified path. If a file with the same name already exists, it will be overwritten.
  4. var formatter = new BinaryFormatter()
    • This line creates a new instance of the BinaryFormatter class. This class is used to serialize and deserialize objects in binary format.
  5. formatter.Serialize(stream, obj);
    • This line calls the Serialize method of the BinaryFormatter object to serialize the obj object into the stream.
    • The BinaryFormatter converts the object into a sequence of bytes and writes these bytes to the file stream.

T Deserialize(string filePath)

  1. The stored file is opened using the FileStream object.
  2. formatter.Deserialize(stream): This method retrieves the object data from the open file stream (stream) using the BinaryFormatter.The deserialized object is cast to the generic type T specified in the method signature.

Step 4. Create an object of customer class and perform the Serialization & Deserialization.

var customer = new Customer
{
    FirstName = "Praveen",
    LastName = "Raveendran"
};

ITransform<Customer> serializer = new BinarySerializer<Customer>();
serializer.Serialize(customer, "customer");
  1. A customer object is created.
  2. Instantiated a BinarySerializer<Customer> object and assigned it to the serializer variable, which is of type ITransform<Customer>.
  3. The Serialize method is invoked, passing the customer object and the desired filePath as arguments. The method serializes the customer object and writes the resulting data to the specified file.

Step 5. Run the code and open the file named customer.

Output

Output

Step 6. Deserialization.

var deserializedCustomer = serializer.Deserialize("customer");
Console.WriteLine($"Customer: {deserializedCustomer.FirstName}, {deserializedCustomer.LastName}");

To deserialize the data, the file path containing the serialized data is passed as a parameter to the Deserialize method.

Step 7. Run the code.

Run Code

By understanding the concepts and best practices of binary serialization in .NET, you can effectively store, transmit, and retrieve your object data in a compact and efficient manner.

Note. The Serialize and Deserialize methods associated with the BinaryFormatter class were marked as obsolete from .NET 7 onwards. This means they are no longer recommended for use due to security vulnerabilities.

Happy Coding!


Similar Articles