Binary serialization in C#

Serializing an object into a binary file is an easy and fast way to persist your objects.

If binary serialization is used to cache objects normally read from an XML file, a database or some other file format, you'll get even more benefits.

After incorporating binary serialization into a C# application that loaded data from an Excel spreadsheet, I was able to get a 33% decrease in execution time by caching the generated object into a binary file. It's a quick-and-dirty way to get a speed increase especially when you're loading a lot of external data that changes, but doesn't change frequently.


The first step for serializing a class into a binary file is to mark the class as Serializable.

Now that your class is ready to be serialized, you can use ObjectSerializer. The ObjectSerializer class below allows anyone to serialize an object into a binary file. Serializing or de-serializing a class marked with the [Serializable] attribute takes no more than 3 lines of C# code.

To serialize an object using ObjectSerializer, first instantiate the ObjectSerializer class. Then use the SaveSerialziedObject() method to serialize the object.


To deserialize the binary file generated from the previous operation, instantiate the ObjectSerializer class. Then use the GetSerializedObject() method to retrieve the original object.

And there you have it... quick-and-dirty binary serialization in C#!

About the Author

Ray Li

Ray is a software engineer and data enthusiast who has been blogging for over a decade. He loves to learn, teach and grow. You’ll usually find him wrangling data, programming and lifehacking.

Comments 1

  1. Code examples in this article show escaped tags. Please use \n instead, since the code example library probably supports presenting text as-is.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.