Serialization and Deserialization in C# with Example

โšก Smart Summary

Serialization in C# converts an object into a stream of bytes so it can be saved to a file or sent between applications; deserialization rebuilds the object. Here you will learn to serialize and deserialize objects with examples.

  • ๐Ÿ”„ What it is: Serialization writes a C# object to a file, and deserialization reads it back.
  • ๐Ÿท๏ธ [Serializable]: A class needs the [Serializable] attribute before it can be serialized.
  • ๐Ÿ’พ Binary format: BinaryFormatter with a FileStream writes the object in binary form.
  • ๐Ÿงฉ Formats: C# also supports XML and JSON serialization for readable output.
  • ๐Ÿค– AI help: AI tools like GitHub Copilot generate serialization code instantly.

C# Serialization and Deserialization

Serialization & Deserialization in C#

The concept of Serialization and deserialization is used whenever data pertaining to objects have to be sent from one application to another. Serialization is used to export application data into a file. The destination application then uses deserialization to extract the data from the application for further use.

Serialization is a concept in which C# class objects are written or serialized to files. Let’ say you had a C# class called Tutorial. And the class has 2 properties of ID and Tutorials name.

Serializing can be used to directly write the data properties of the Tutorial class to a file. Deserialization is used to read the data from the file and construct the Tutorial object again.

Types of Serialization in C#

C# supports several serialization formats, and you choose one based on where the data will be used. The main types are listed below.

  • Binary serialization converts an object into a compact binary stream. It is fast but not human-readable and is tied to .NET.
  • XML serialization uses the XmlSerializer class to write an objectโ€™s public properties to a readable XML file.
  • JSON serialization uses System.Text.Json or Newtonsoft.Json to produce lightweight JSON, the most common format for web APIs.
  • SOAP serialization formats data as SOAP messages for older web services.

How to Serialize an Object in C#

Let’s look at an example of how we can achieve this.

In our example, we are going to perform the below high-level steps in the code

  1. Create a class called Tutorial which has 2 properties, namely ID, and Name
  2. We will then create an object from the class and assign a value of “1” to the ID property and a value of “.Net” to the name property.
  3. We will then use serialization to serialize the above object to a file called Example.txt
  4. Finally, we will use deserialization to deserialize the object from the file and display the values in the Console.

Enter the below code in the program.cs file of the console application.

Step 1) Add the class.

The first step is to add the class which will be used for serialization

Serialize an Object in C#

Code Explanation:-

  1. The class which needs to be serialized needs to have the [Serializable] attribute. This is a keyword in C#. This keyword is then attached to the Tutorial class. If you don’t mention this attribute, you will get an error when you try to serialize the class.
  2. Next is the definition of the class which will be serialized. Here we are defining a class called “Tutorial” and providing 2 properties, one is “ID” and the other is “Name.”

Step 2) Create the object.

In this step, first we will create the object of the Tutorial class and serialize it to the file called Example.txt

Serialize an Object in C#

Code Explanation:-

  1. First, we create an object of the Tutorial class. We then assign the value of “1” to ID and “.net” to the name property.
  2. We then use the formatter class which is used to serialize or convert the object to a binary format. The data in the file in serialization is done in binary format. Next, we create a file stream object. The file stream object is used to open the file Example.txt for writing purposes. The keywords FileMode.Create and FileMode.Write is used to specifically mention that the file should be opened for writing purposes.
  3. Finally, we use the Serialize method to transfer the binary data to the file. We then close the stream, since the write operation is complete.

Step 3) Use deserialization.

Finally to ensure that the data is present in the file, we use deserialization to deserialize the object from the file.

Serialize an Object in C#

using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace DemoApplication
{
  [Serializable]
  class Tutorial
  {
  public int ID;
  public String Name;
   static void Main(string[] args)
   {
    Tutorial obj = new Tutorial();
    obj.ID = 1;
    obj.Name = ".Net";

    IFormatter formatter = new BinaryFormatter();
    Stream stream = new FileStream(@"E:\ExampleNew.txt",FileMode.Create,FileAccess.Write);

    formatter.Serialize(stream, obj);
    stream.Close();

    stream = new FileStream(@"E:\ExampleNew.txt",FileMode.Open,FileAccess.Read);
    Tutorial objnew = (Tutorial)formatter.Deserialize(stream);

    Console.WriteLine(objnew.ID);
    Console.WriteLine(objnew.Name);

    Console.ReadKey();
  }
 }
}

Code Explanation:-

  1. We create the object “stream” to open the file Example.txt in reading only mode.
  2. We then use the formatter class which is used to deserialize the object, which is stored in the Example.txt file. The object returned is set to the object objnew.
  3. Finally, we display the properties of the object “objnew” to the console using the “ID” and “name” properties.

When the above code is set, and the project is run using Visual Studio, you will get the below output.

Output:-

Serialize an Object in C#

You can see from the above output that the values from the file were deserialized properly and displayed in the console.

JSON Serialization in C#

JSON is the most widely used format for modern applications and web APIs. The built-in System.Text.Json namespace serializes and deserializes objects with a single method call, as shown below.

using System;
using System.Text.Json;
namespace DemoApplication
{
  class Tutorial
  {
    public int ID { get; set; }
    public string Name { get; set; }
  }
  class Program
  {
    static void Main(string[] args)
    {
      Tutorial obj = new Tutorial { ID = 1, Name = ".Net" };
      string json = JsonSerializer.Serialize(obj);
      Console.WriteLine(json);

      Tutorial objnew = (Tutorial)JsonSerializer.Deserialize(json, typeof(Tutorial));
      Console.WriteLine(objnew.Name);
      Console.ReadKey();
    }
  }
}

Output:

{"ID":1,"Name":".Net"}
.Net

FAQs

Serialization converts a C# object into a stream of bytes (binary, XML, or JSON) so it can be saved to a file or sent to another application. Deserialization rebuilds the object from that data.

The [Serializable] attribute marks a class so its objects can be serialized. Without it, binary serialization throws an exception when you try to write the object to a file.

C# supports binary serialization (compact, .NET-only), XML serialization via XmlSerializer, JSON serialization via System.Text.Json, and SOAP serialization for older web services.

Serialization writes an object’s data to a file or stream, while deserialization reads that data back and reconstructs the original object in memory.

BinaryFormatter is now obsolete and considered insecure because it can execute harmful code during deserialization. Microsoft recommends System.Text.Json or XmlSerializer for new applications.

AI assistants like GitHub Copilot autocomplete Serialize and Deserialize calls, add the [Serializable] attribute, and generate JSON or XML serialization code from a short comment.

Yes. AI-powered tools generate model classes, choose between JSON, XML, and binary formats, and add error handling so your serialization code is safe and complete.

Binary serialization uses System.Runtime.Serialization.Formatters.Binary, JSON uses System.Text.Json, and XML uses System.Xml.Serialization.

Summarize this post with: