DEV Community

Nick
Nick

Posted on

What is Serialization and Deserialization in C#?

Serialization is the process of converting an object into a stream of bytes in order to store it or transmit it over a network. Deserialization is the process of converting that stream of bytes back into an object. In C#, serialization and deserialization are commonly used when working with XML and JSON data, as well as when sending and receiving data over a network.

To serialize an object in C#, you can use the built-in XmlSerializer or JsonSerializer classes. Here is an example of serializing an object into XML format:

using System;
using System.IO;
using System.Xml.Serialization;

// Define a class to be serialized
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        // Create an instance of the Person class
        Person person = new Person { Name = "Alice", Age = 30 };

        // Create a FileStream to write the serialized data to a file
        FileStream fs = new FileStream("person.xml", FileMode.Create);

        // Create an XmlSerializer object
        XmlSerializer serializer = new XmlSerializer(typeof(Person));

        // Serialize the object and write it to the file
        serializer.Serialize(fs, person);

        // Close the file stream
        fs.Close();
    }
}
Enter fullscreen mode Exit fullscreen mode

To deserialize the XML data back into an object, you can use the XmlSerializer class as well. Here is an example:

using System;
using System.IO;
using System.Xml.Serialization;

class Program
{
    static void Main()
    {
        // Create a FileStream to read the serialized data from a file
        FileStream fs = new FileStream("person.xml", FileMode.Open);

        // Create an XmlSerializer object
        XmlSerializer serializer = new XmlSerializer(typeof(Person));

        // Deserialize the object from the file
        Person person = (Person)serializer.Deserialize(fs);

        // Close the file stream
        fs.Close();

        // Display the deserialized object
        Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Serialization and deserialization are powerful tools in C# that allow you to easily store and transmit data in a structured format. By using serialization, you can save time and effort when working with complex data structures in your applications.

Top comments (0)