Serialize Your Objects in C#: A Practical How‑To Guide

Serialization is a fundamental concept in C# that enables developers to convert objects into a format suitable for storage or transmission and then reconstruct them later. Whether you are working with JSON, XML, binary, or custom serialization methods, understanding how to serialize objects efficiently is crucial for performance and maintainability.

In this guide, we will explore different serialization techniques in C#, their use cases, best practices, and common pitfalls to avoid.

What Is Serialization?

Serialization is the process of converting an object’s state into a format that can be stored in a file, database, or transmitted over a network. The opposite process, called deserialization, reconstructs the object from the serialized data.

Common Use Cases for Serialization:

  • Saving application state: Persisting objects to files or databases.

  • Inter-process communication: Transmitting objects between applications or services.

  • Caching data: Storing serialized objects in a cache for quick retrieval.

  • Web APIs: Sending structured data (like JSON) to clients in ASP.NET Core applications.

JSON Serialization in C#

One of the most common serialization methods in modern C# applications is JSON serialization. .NET provides System.Text.Json for this purpose.

Using System.Text.Json

using System;
using System.Text.Json;

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

class Program
{
    static void Main()
    {
        var person = new Person { Name = "John Doe", Age = 30 };
        
        // Serialize
        string jsonString = JsonSerializer.Serialize(person);
        Console.WriteLine(jsonString);
        
        // Deserialize
        Person deserializedPerson = JsonSerializer.Deserialize<Person>(jsonString);
        Console.WriteLine(deserializedPerson.Name);
    }
}

Advantages of System.Text.Json:

  • Built into .NET Core and .NET 5+

  • Fast and efficient serialization

  • Supports custom converters for complex scenarios

Customizing JSON Serialization

Sometimes, you need to customize the serialization process. This can be achieved using JsonSerializerOptions.

var options = new JsonSerializerOptions
{
    WriteIndented = true, // Pretty-print JSON
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
string jsonString = JsonSerializer.Serialize(person, options);

XML Serialization in C#

For legacy systems or compatibility with XML-based APIs, C# provides System.Xml.Serialization.

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

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

class Program
{
    static void Main()
    {
        var product = new Product { Name = "Laptop", Price = 999.99m };
        XmlSerializer serializer = new XmlSerializer(typeof(Product));
        
        using (StringWriter writer = new StringWriter())
        {
            serializer.Serialize(writer, product);
            Console.WriteLine(writer.ToString());
        }
    }
}

When to Use XML Serialization:

  • Working with legacy systems that require XML.

  • Interoperability with non-.NET platforms.

  • Configuration files where readability is important.

Binary Serialization (Deprecated in .NET Core)

Binary serialization is a fast but less human-readable method of serialization. It requires objects to be marked with [Serializable].

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

[Serializable]
public class Employee
{
    public string Name { get; set; }
    public int ID { get; set; }
}

class Program
{
    static void Main()
    {
        var employee = new Employee { Name = "Alice", ID = 101 };
        BinaryFormatter formatter = new BinaryFormatter();
        
        using (MemoryStream stream = new MemoryStream())
        {
            formatter.Serialize(stream, employee);
            stream.Position = 0;
            Employee deserializedEmployee = (Employee)formatter.Deserialize(stream);
            Console.WriteLine(deserializedEmployee.Name);
        }
    }
}

Note: Binary serialization is considered unsafe in .NET Core due to security risks, and Microsoft recommends using JSON or XML instead.

Custom Serialization with ISerializable

For more control over serialization, implement the ISerializable interface.

using System;
using System.Runtime.Serialization;

[Serializable]
public class CustomObject : ISerializable
{
    public string Data { get; set; }

    public CustomObject() { }
    
    protected CustomObject(SerializationInfo info, StreamingContext context)
    {
        Data = info.GetString("Data");
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("Data", Data);
    }
}

Best Practices for Serialization in C#

  1. Use JSON serialization for most scenarios: System.Text.Json is the recommended approach for performance and security.

  2. Avoid binary serialization in .NET Core: It is deprecated due to security vulnerabilities.

  3. Optimize performance with caching: Serialize objects once and reuse the serialized data when possible.

  4. Handle circular references: Use [JsonIgnore] or serialization settings to avoid infinite loops.

  5. Use DataContract for interoperability: When working with WCF or external systems.

Conclusion

Serialization is a crucial technique in C# applications, enabling data persistence, transfer, and caching. By leveraging JSON, XML, and custom serialization methods effectively, developers can optimize performance and maintainability. Always choose the appropriate serialization method based on security, readability, and system requirements.

By following best practices and understanding serialization pitfalls, you can build robust and efficient .NET applications.