Various Serializations in C#

What is Serialization in C#?

**Serialization** is the process of converting an object into a format that can be stored or transferred and later reconstructed. C# provides multiple serialization techniques, each suited for specific needs.

Types of Serialization in C#

The following are different serialization techniques in C#:

Serialization Type Description Use Case
Binary Serialization Stores object data in a **compact binary format**. Used for **performance-efficient** storage and communication.
XML Serialization Stores object data in a **structured XML format**. Used for **configuration files and web services**.
JSON Serialization Stores object data in a **lightweight JSON format**. Used for **REST APIs and data exchange**.
Custom Serialization Allows **manual control** over the serialization process. Used when **custom serialization logic** is needed.

Binary Serialization

Binary serialization stores objects in a **compact format** but is **not human-readable**.

Example: Binary Serialization

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

[Serializable]
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// Writing Binary Data
class Program
{
    static void Main()
    {
        Person person = new Person { Name = "Alice", Age = 30 };
        BinaryFormatter formatter = new BinaryFormatter();

        using (FileStream stream = new FileStream("person.dat", FileMode.Create))
        {
            formatter.Serialize(stream, person);
        }

        Console.WriteLine("Object serialized to binary.");
    }
}

// Output:
// Object serialized to binary.
        

**[Serializable]** is required for binary serialization.

XML Serialization

XML serialization stores object data in a **structured XML format**.

Example: XML Serialization

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

[Serializable]
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// Writing XML Data
class Program
{
    static void Main()
    {
        Person person = new Person { Name = "Bob", Age = 35 };
        XmlSerializer serializer = new XmlSerializer(typeof(Person));

        using (FileStream stream = new FileStream("person.xml", FileMode.Create))
        {
            serializer.Serialize(stream, person);
        }

        Console.WriteLine("Object serialized to XML.");
    }
}

// Output:
// Object serialized to XML.
        

XML serialization is useful for **configurations and web services**.

JSON Serialization

JSON serialization is widely used for **REST APIs and data exchange**.

Example: JSON Serialization

using System;
using System.Text.Json;
using System.IO;

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// Writing JSON Data
class Program
{
    static void Main()
    {
        Person person = new Person { Name = "Charlie", Age = 40 };
        string json = JsonSerializer.Serialize(person);

        File.WriteAllText("person.json", json);
        Console.WriteLine("Object serialized to JSON.");
    }
}

// Output:
// Object serialized to JSON.
        

JSON serialization is best for **web and mobile applications**.

Custom Serialization

Custom serialization allows defining how objects should be serialized.

Example: Custom Serialization Using ISerializable

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

[Serializable]
class Person : ISerializable
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person() { }

    protected Person(SerializationInfo info, StreamingContext context)
    {
        Name = info.GetString("PersonName");
        Age = info.GetInt32("PersonAge");
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("PersonName", Name);
        info.AddValue("PersonAge", Age);
    }
}

// Writing Custom Serialization
class Program
{
    static void Main()
    {
        Person person = new Person { Name = "David", Age = 45 };
        BinaryFormatter formatter = new BinaryFormatter();

        using (FileStream stream = new FileStream("person_custom.dat", FileMode.Create))
        {
            formatter.Serialize(stream, person);
        }

        Console.WriteLine("Object serialized with custom logic.");
    }
}

// Output:
// Object serialized with custom logic.
        

**ISerializable** allows **custom serialization logic**.