Working with Serialization in C#

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

C# Programming Guide

When working with applications, C# programmers will often need to store data in a persistent or non-persistent storage medium. Developers might also need to transmit data over the wire. The sender and the receiver process can be in the same application, different systems on the same network, or even other systems in networks spread across geographical boundaries. Enter serialization.

Serialization refers to the process of converting data into a format that may be stored or transmitted between systems across a network or networks. This format can be a text file, XML document, a binary stream or any other standard format used for storing objects.

Read: C# Tools for Code Quality

What is Serialization in C#?

You can use serialization to turn an object into a stream of bytes or to store the state of an object to be able to recreate it later. For example, if you want to send some data from one server to another over the network, serialization will allow you to do that without requiring any knowledge about how things work on both sides of this communication channel.

Serialization can be used to persist data, such as user preferences and settings, across application sessions. You can also deserialize, or convert the serialized data back to the original piece of data.

Serialization is useful when we want to save the state of an object or send it over the network. The process of serializing an object involves converting it into bytes, which then can be stored (or transmitted) in a file or over a network.

Serialization can be of the following types:

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

Why Do Developers Need Serialization?

Serialization is a useful technique for storing objects as files, sending data over the network, and communicating with databases. It can also be used to simplify communication between different systems that use different formats for their data structures. For example, when you send an object over the network using serialization, the receiving program can deserialize it as required.

This makes it possible for a program written in C# to communicate with another program written in Java or Python because they’re both able to read whatever format they receive from each other—they don’t need to know what kind of data structure was used by the sending program.

How to Implement Serialization in C# and .NET

To implement serialization in .NET and C#, developers have two options:

  • Use the [Serializable] attribute
  • Implement the ISerializable Interface

Using the [Serializable] Attribute in C#

You can work with serialization in .NET and C# by leveraging the System.Runtime.Serialization namespace (i..e, including this namespace in your program).

The [Serializable] attribute in C# allows you to tell the compiler that your type can be serialized by default. The following program illustrates how you can make a class serializable in C#:

[Serializable]
public class Student
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

The ISerializable Interface: Implementing Custom Serialization

To implement custom serialization in C#, you can take advantage of the ISerializable interface. This interface provides methods that allow you to control how your type is serialized, including writing custom classes and properties. The program given below shows how you can implement custom serialization.

public class Student : ISerializable
{
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        //Write your custom code here
    }
}

Read: Productivity Tools for .NET Developers

JSON Serialization in C#

JSON serialization is the process of converting an object into a JSON string. It is used a lot in applications, because it is easier to understand than XML and more compact than XML. Since JSON is supported by all modern programming languages, it is a great choice when you need to exchange data between different systems. You can easily convert your objects into JSON strings and send them over the network for processing.

XML Serialization in C#

XML serialization is one of the ways to convert an object into a string representation. It is used to transport the data over the network or to save it in disk. XML serialization transforms an object’s public fields and properties, method arguments, and return values into an XML stream.

XML serialization creates classes with strongly typed properties and fields stored or sent in a serial format (in this case, in XML). Since XML is an open standard, any program written in any language can parse the XML stream regardless of the platform. There are two methods which need to be implemented in order for your class to work with XML serialization, they are:

  • GetObjectData() – It allows you to add data into an XML document at runtime; this method returns void and takes an XmlDictionaryWriter object as parameter which contains all data and settings needed by us during serialization process.
  • ReadXml() – This method reads an XML document back into our class so that we can access its properties again like any other class

Binary Serialization in C#

Binary serialization is the process of converting an object into a stream of bytes. This stream can then be stored in a file or transmitted over a network. When the stream is read back into memory, it can be converted into an object again.

Binary serialization is a very efficient way to store or transmit data. The main downside is that the data is not human-readable. If you need to be able to read the data, you will need to use a different method such as XML Serialization.

To serialize an object using binary serialization, you first need to create a BinaryFormatter object. This object has a Serialize() method which takes two parameters – the object to serialize and the stream to write the data to. The following example shows how to serialize an object and write it to a file in C#:

using (FileStream fs = new FileStream("data.dat", FileMode.Create))
{
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(fs, myObject);
}

To deserialize an object, you should use the Deserialize() method of the BinaryFormatter class. This method takes a stream to read from and an object to initialize the deserialized object with. The following code example shows how to deserialize an object that was serialized earlier using binary serialization:

FileStream fs = new FileStream("data.dat", FileMode.Open); 
BinaryFormatter formatter = new BinaryFormatter(); 
MyClass myObject = (MyClass)formatter.Deserialize(fs);

SOAP Serialization in C#

Simple Object Access Protocol (commonly known as SOAP) serialization is yet another option to serialize data. You can take advantage of SOAP serialization when you want to transfer objects across applications with diverse architectures. You should include the Serialization.Formatters.Soap namespace in your program if you want to use SOAP serialization.

Final Thoughts on Serialization in C#

Note that you cannot serialize an interface in C#. This is because serialization works only on data. An interface does not have data – it only contains method declarations or method definitions (interface methods can have default implementations from C# 8 onwards).

Read more C# programming tutorials and software development guides.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read