What is Serialization in C#?

Learn via video courses
Topics Covered

Overview

Serialization in C# helps for storing data in databases or files and sending it across networks between applications or systems. Serialization maintains data integrity and promotes smooth communication across systems and locations by transforming items into an appropriate format.

What is Serialization in C#?

The process of turning objects into a storable or transportable format is known as serialization in C#. It enables data to be saved to files or transported over networks while retaining its structure. Binary, XML, and JSON serialization are common approaches for simplifying data transmission and object state persistence.

serialization in csharp

Serialization maintains data integrity and facilitates smooth communication across several systems and locations by transforming data into an appropriate format. It fulfills several functions, including data persistence, state preservation, and interoperability, making it an essential component of developing strong and efficient software systems. During deserialization, data is reconstructed back into its original object form. Serialization is vital for state persistence, inter-platform communication, and web APIs. Here are following types of Serializers:

  • Binary Serialization: This method converts objects into a binary format, which is more compact and efficient for storage and transmission within the .NET ecosystem.
  • SOAP Serialization: SOAP (Simple Object Access Protocol) serialization is primarily used in web services to enable communication between different platforms and systems using XML-based messages.
  • XML Serialization: This approach converts objects into XML format, which is human-readable and widely supported across different platforms, making it suitable for inter-platform communication.
  • JSON Serialization: JSON (JavaScript Object Notation) serialization converts objects into a lightweight and readable format, commonly used for web APIs and data interchange in web development.
  • Custom Serialization: Developers can implement custom serialization logic using interfaces like ISerializable in C#, allowing them to control how objects are serialized and deserialized based on their specific requirements

The SerializableAttribute in C#

SerializableAttribute is a C# attribute that indicates that a class can be converted into a format that can be easily saved or transferred across various platforms or applications. When a class is declared as [Serializable], its objects can be transformed into a stream of bytes, generally for storage on disc, transmission over a network, or database storage. SerializableAttribute is in the System namespace and is included in the .NET Framework and .NET Core libraries. The attribute itself has no properties or methods; it only indicates to the runtime that the class should be serializable.

Involved Namespaces

The following namespaces are involved in the serialization process in C#:

  • System.Runtime.Serialization: This namespace contains the classes and interfaces required for custom serialization and deserialization. It contains the main serialization architecture as well as properties that enable developers to control the serialization process. Some important types in this namespace are:

    • ISerializable: This interface is used for custom serialization of objects. By implementing this interface, you can define how an object is serialized and deserialized.
    • SerializationInfo: This class holds the data needed for serialization and deserialization of an object that implements the ISerializable interface.
    • StreamingContext: This class specifies the source and destination of the serialized data and provides additional context information during the serialization and deserialization process.
  • System.Runtime.Serialization.Formatters.Binary: This namespace contains classes that enable binary serialization, which converts objects into a binary format for easy persistence and transmission.The main class in this namespace is:

    • BinaryFormatter: This class provides methods to serialize and deserialize objects using binary format. It is commonly used in conjunction with the MemoryStream or FileStream classes to read from or write to memory or disk, respectively.

Examples

Let's see an example of Serializing a Person Object to JSON Format in C#. In this example, we have a simple Person class with two properties: Name and Age. We then create a new Person object with some sample data. Using the SerializeToJson method, we serialize the Person object to a JSON string.

Example 1:

Output:

The SerializeToJson method uses System.Text.Json.JsonSerializer to convert the object to JSON format. We specify JsonSerializerOptions with WriteIndented set to true, making the JSON output indented for better readability.

Next, we use the DeserializeFromJson method to deserialize the JSON string back into a Person object. This method uses the JsonSerializer.Deserialize<T> method to perform deserialization, where T represents the type of the object we want to deserialize (in this case, Person).

Finally, we display the deserialized Person object's Name and Age properties to verify that the deserialization process successfully reconstructed the object from the JSON string.

Example 2: Let's see another example to serialize an array of objects in C#:

Output:

The above example uses System.Text.Json to serialize an array of custom objects, represented by the Person class. First, the class is defined with two properties, Name and Age. Then, an array persons is created, containing two Person objects. Using JsonSerializer.Serialize, the array is converted to a JSON-formatted string. Finally, the JSON string is printed to the console. The resulting JSON represents an array of objects with Name and Age properties, corresponding to the data of the Person objects in the array.

FAQs

Q. What is serialization in C#, and why is it important?

A: Serialization in C# refers to the process of converting an object's state into a format that can be easily stored, transmitted, or reconstructed. It is essential because it allows objects to be persisted to disk, transmitted over networks, or shared between different applications and platforms while preserving their state and structure.

Q. How does serialization work in C#?

A: Serialization in C# involves converting object data into a stream of bytes. This process typically involves two main steps: serialization (converting objects into a byte stream) and deserialization (reconstructing objects from the byte stream). C# provides built-in serialization mechanisms like binary, XML, and JSON serialization, or developers can implement custom serialization using interfaces like ISerializable.

Q. When should I use custom serialization in C#?

A: Custom serialization is beneficial when you need fine-grained control over the serialization process or when the default serialization mechanisms don't meet specific requirements. You can implement the ISerializable interface to define how an object is serialized and deserialized, allowing you to manage sensitive data, handle versioning, or optimize serialization for specific scenarios.

Conclusion

  • Serialization in C# is a process that transforms objects into a storable or transportable format, allowing data to be saved to files or transmitted across networks while preserving its structure and state.
  • It is essential for data persistence, state preservation, and interoperability, making it a fundamental component of building robust and efficient software systems.
  • C# provides various built-in serializers such as Binary Serialization, SOAP Serialization, XML Serialization, and JSON Serialization, catering to different use cases and formats.
  • Custom Serialization can be implemented using interfaces like ISerializable in C#, granting developers fine-grained control over the serialization and deserialization process to accommodate specific requirements.
  • The involved namespaces, System.Runtime.Serialization and System.Runtime.Serialization.Formatters.Binary, provide the necessary classes and interfaces for custom serialization and binary serialization in C#.