Serialization and Deserialization in C# with Examples

Serialization in CSharp
Serialization in C#

Difference between serialization and deserialization in C#

Serialization is the process of converting objects into a byte stream to make them suitable for storage in memory, files, or databases. On the other hand, deserialization is the reverse process of serialization, which allows you to read an object from a byte stream.

What is Serialization and Deserialization in C#?

Serialization in C# is a process of converting an object into a sequence of bytes. It means putting an object into a form that can be transported across the network and stored in a file, database, or memory. 

You can use serialization to save an object’s state and reconstruct it when needed. The reverse process of serialization is called deserialization.

The terms “serialization and deserialization” are used when data needs to be transferred between applications.

C# SerializableAttribute Class

To serialize an object such as a class, you should apply the Serializable attribute. If there are specific fields in the class that you do not want to be serialized, you should mark them with the NonSerialized attribute.

When an object is serialized, it is converted into a stream of data that includes metadata about that specific object type, such as its version and assembly name, etc. 

When you try to serialize a type that does not have the Serializable attribute, it may throw an exception.

Types of Serialization

The following are the types of serialization:

  • Binary Serialization
  • XML Serialization
  • JSON Serialization
  • SOAP Serialization

Example:

The following is a simple example of serializing a class in C#.

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

[Serializable]
class Employee
{
    private int id;
    private string name;
    [NonSerialized()]
    private string address;

    public Employee(int rollno, string name, string address)
    {
        this.id = rollno;
        this.name = name;
        this.address = address;
    }
}
public class SerializationExample
{
    public static void Main(string[] args)
    {
       // Initialize an object
        Employee empObject = new Employee(101, "Shekh Ali","Delhi");
        // Create the file stream
        FileStream stream = new FileStream("C:\\MyData\\SerializationExample.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(stream, empObject);
        stream.Close();
    }
}

Code Explanation:

  • First, create an object of the Employee class. Then assign the ID the value ‘101’, the name ‘Shekh Ali’, and the value “Delhi” to the address property.
  • Next, create a file stream object to open/create the “SerializationExample.txt” file for writing purposes. Then use the Formatter class to serialize or convert the object to binary format.
  • Finally, the Serialize method transfers the binary data to the file. Close the stream once you’ve finished writing.
  • Here, we are serializing the Employee class by adding the Serializable attribute. Only we left the address field, which is not supposed to be serialized; that’s why we marked it with the NonSerialized attribute.

C# Deserialization

In C#, deserialization is the opposite of serialization. It involves reading and restoring serialized data to an object so that we can load it into memory.

This process allows us to recreate an object from a stream of bytes when needed.

Serialization and Deserialization in CSharp
Deserialization in C#

Example:

In the following example, we will use the BinaryFormatter.Deserialize(stream) method to deserialize the stream from the “SerializationExample.txt” file.

 // Create an object of the BinaryFormatter class.
BinaryFormatter formatter = new BinaryFormatter();
// Create a file stream object
FileStream stream = new FileStream("C:\\MyData\\SerializationExample.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);    
Employee employee = (Employee)formatter.Deserialize(stream);
Console.WriteLine($"Id: {employee.id} Name: {employee.name}");      
stream.Close();
Console.ReadLine();

After running the project, you will get the result displayed below.

Deserialization in C# output

Code explanation for deserializing the object:

  • First, create a stream object to read the serialized output.
  • Then create an object of BinaryFormatter class.
  • Finally, call the BinaryFormatter.Deserialize(stream) method to deserialize the stream from a file, and cast it to the specific type.

Serializing Object to XML in C#

The .NET Framework includes powerful objects that can serialize any object to XML format. The  System.Xml.Serialization  namespace provides the capability to convert the public fields and properties of an object into an XML stream.

using System;
using System.IO;
using System.Xml.Serialization;
public class Employee
{
    public int id;
    public string name;
    public string address;  
}
public class XMLSerializationExample
{
    public static void Main(string[] args)
    {
        // Create an object of the employee class.
        Employee employee = new Employee();
        employee.id = 101;
        employee.name = "Shekh Ali";
        employee.address = "Delhi";

        // Create an instance of the XmlSerializer to accepts the object type as the parameter.
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(Employee));

        using (TextWriter txtWriter = new StreamWriter(@"C:\MyData\XMLSerializationExample.xml"))
        {
            xmlSerializer.Serialize(txtWriter, employee);
        }

        //Opening file to read XML data
        FileStream fileStream = new FileStream(@"C:\MyData\XMLSerializationExample.xml",
        FileMode.Open);
        XmlSerializer serializer = new XmlSerializer(typeof(Employee));
        //Calling Deserialize() to deserialize data from the file
        Employee emp = (Employee)serializer.Deserialize(fileStream);
        Console.WriteLine($"Id: {emp.id} Name: {emp.name} Address: {emp.address}");
    }
}

When we will run the above program, the XML file will generate in the specified location.

XMLSerialization in csharp
XMLSerialization in C#

Deserialize an XML file in c#:

The XmlSerializer.Deserialize(Stream) method is used to deserialize the XML document contained by the specified Stream.

deserialize an XML file in csharp
Image: Deserialize an XML file.

JSON Serialization in C#

JSON (JavaScript Object Notation) is a lightweight data format designed for running JavaScript on websites. JSON is now widely used on the web for storing and transporting data.

In C#, the System.Text.Json namespace is used to serialize and deserialize from JSON.

Example:

The following is a console application program created in Visual Studio to demonstrate JSON serialization.

using System;
using System.IO;
using System.Text.Json;
public class Employee
{
    public int id { get; set; }
    public string name { get; set; }
    public string address { get; set; }
}
public class JSONSerializationExample
{
    public static void Main(string[] args)
    {
        // Create an object of the employee class.
        Employee employee = new()
        {
            id = 101,
            name = "Shekh Ali",
            address = "Delhi"
        };

        string fileName = @"C:\MyData\Employee.json";
        string jsonString = JsonSerializer.Serialize(employee);
        File.WriteAllText(fileName, jsonString);

        Console.WriteLine(File.ReadAllText(fileName));
        Console.ReadLine();

        // Output: {"id":101,"name":"Shekh Ali","address":"Delhi"}

    }
}

SOAP (Simple Object Access Protocol) Serialization

SOAP (Simple Object Access Protocol) is a way to serialize and transmit data over a network using XML. It is a widely used protocol for exchanging information in a decentralized, distributed environment.

In C#, you can use System.Xml.Serialization.SoapSerializer class to serialize and deserialize objects using the SOAP format.

Example:

The following is an example of how you can use this class to serialize an object:

// Define a class to be serialized
[Serializable]
public class Employee
{
  public int ID { get; set; }
  public string Name { get; set; }
  public string Address { get; set; }
}

// Create an instance of the class
Employee emp = new Employee { ID = 101, Name = "Shekh Ali", Address = "Delhi" };

// Create a file stream to write the serialized data to
using (FileStream stream = File.Create(@"C:\employee.xml"))
{
  // Create a SOAP serializer
  SoapFormatter serializer = new SoapFormatter();

  // Serialize the object to the file stream
  serializer.Serialize(stream, emp);
}

you can use the Deserialize method of the SoapFormatter class to deserialize the object.

// Create a file stream to read the serialized data from
using (FileStream stream = File.OpenRead("employee.xml"))
{
  // Create a SOAP serializer
  SoapFormatter serializer = new SoapFormatter();

  // Deserialize the object from the file stream
  Employee emp = (Employee)serializer.Deserialize(stream);
}

We should keep in mind that the SoapSerializer class is part of the System.Xml.Serialization namespace, so we will need to include this namespace in our code using the using directive.

FAQ

The following are some common questions and answers about serialization and deserialization in C#:

Q: What is serialization in C#?

Ans: Serialization is the process of converting an object into a stream of data that can be stored or transmitted over a network.
It allows you to save the state of an object or transfer it to another system.

Q: How many different serialization types are there in C#?

Ans: The three main serialization types offered by C# .NET are binary, soap, and XML serialization.

Q: What are the advantages of serialization?

1. It can be used to send an object from one application to another.
2. To pass an object from one domain to another.
3. To pass an object through a firewall as a JSON or XML string.
4. To Maintain security or user-specific information across applications.

Q: What types of data are acceptable in JSON?

Ans: String, Array, Null, Object, Number, Boolean.

Q: What is the difference between soap and XML serialization in C#?

XML serialization can be used to serialize an object into an XML stream that conforms to the SOAP specification. SOAP is an XML-based protocol developed specifically for transporting procedure calls using XML. You can use the XmlSerializer class to serialize or deserialize objects.

SOAP serialization uses classes from the System.Runtime.Serialization namespace, and XML serialization use classes from the System.Xml.Serialization namespace.

Q: How to Serialize an Object in C#?

To serialize an object in C#, you need to mark it with the [Serializable] attribute and then use a serialization method to convert it to a stream of data.

For example, you can use the BinaryFormatter.Serialize() method to serialize an object to a binary stream.

Q: What is deserialization in C#?

A: Deserialization is the opposite of serialization. It involves reading and restoring serialized data to an object so that it can be loaded into memory.
This allows you to recreate an object from a stream of data that has been saved or transmitted over a network.

Q: Can all objects be serialized in C#?

A: No, all objects can’t be serialized in C#. In order to be serialized, an object must be marked with the [Serializable] attribute and all of its members must also be serializable. Objects that contain references to non-serializable objects or circular references cannot be serialized.

Summary:

This article introduces the “serialization and deserialization” technique. The steps are clearly and comprehensively explained for easy understanding. These techniques are used quite often when developing applications that communicate over networks.

Serialization is the process of converting an object into a form so that it can be stored in a file, database, or memory; or transferred across the network. 

Its main purpose is to save the state of an object so that it can be recreated when needed. The reverse process of serialization is called deserialization.

I hope you found this article on “serialization and deserialization in c#” to be interesting. If you find something incorrect or wish to offer more information regarding the subjects discussed here, please leave a comment below.

References: MSDN- Serialization (C#), JavaTpoint- C#-Serialization

Articles to Check Out:

Shekh Ali
5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments