XmlSerializer
BinaryFormatter
serialization
C#
.NET

What are the differences between the XmlSerializer and BinaryFormatter

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

XmlSerializer and BinaryFormatter were both used in older .NET applications, but modern guidance treats them very differently. XmlSerializer remains usable for contract-based XML interchange, while BinaryFormatter is obsolete and unsafe for general deserialization. Understanding the differences is important for legacy maintenance and migration planning. For modern systems, serializer choice should prioritize safety and contract evolution over legacy convenience.

Serialization Format and Interoperability

XmlSerializer produces readable XML text with explicit element names. That makes payloads easier to inspect and share with non-.NET systems.

csharp
1using System.IO;
2using System.Xml.Serialization;
3
4public class Person
5{
6    public string Name { get; set; } = string.Empty;
7    public int Age { get; set; }
8}
9
10var p = new Person { Name = "Ada", Age = 30 };
11var xml = new XmlSerializer(typeof(Person));
12
13using var sw = new StringWriter();
14xml.Serialize(sw, p);
15Console.WriteLine(sw.ToString());

BinaryFormatter writes binary payloads tied to internal .NET type metadata. Payloads are compact but opaque and tightly coupled to runtime type shapes.

Security Profile Is the Biggest Difference

The most important modern point is security:

  • BinaryFormatter deserialization can be exploited with crafted payloads.
  • It should not be used for untrusted or semi-trusted data.
  • New code should avoid it entirely.

Microsoft has marked BinaryFormatter obsolete for security reasons. For most applications, modern alternatives such as System.Text.Json or DataContractSerializer are safer defaults.

Type Model and Control

XmlSerializer works from public properties and fields and typically expects a parameterless constructor. It encourages explicit data contracts.

csharp
1public class OrderDto
2{
3    public string Id { get; set; } = string.Empty;
4    public decimal Total { get; set; }
5}

BinaryFormatter historically serialized rich object graphs automatically, including private state in many cases. That flexibility reduced ceremony but increased fragility and security risk.

Versioning and Compatibility Behavior

Contract-based serializers usually make version evolution clearer:

  • add optional fields with defaults
  • maintain backward reading behavior
  • document schema changes explicitly

Binary graph snapshots tied to internal class structure are harder to evolve safely. Simple refactors such as renaming members or moving namespaces can break deserialization.

For long-lived systems, explicit contracts are usually easier to maintain.

Performance and Payload Tradeoffs

Text formats can be larger than binary formats, but modern serializers are fast enough for many workloads. If performance is critical, benchmark safe options instead of relying on legacy assumptions.

Example JSON baseline with System.Text.Json:

csharp
1using System.Text.Json;
2
3var payload = JsonSerializer.Serialize(p);
4var restored = JsonSerializer.Deserialize<Person>(payload);
5Console.WriteLine(restored?.Name);

When size is critical, evaluate protocol buffers or MessagePack in addition to JSON and XML.

Migration Strategy Away from BinaryFormatter

For legacy applications, migrate incrementally:

  1. inventory all serialization and deserialization entry points
  2. classify trusted and untrusted data paths
  3. replace high-risk external deserialization first
  4. add compatibility readers for historical stored data
  5. remove BinaryFormatter usage fully after validation

This phased plan reduces operational risk.

Example of Safe Contract-Oriented Serialization

Even if you still need XML for interoperability, keep contracts explicit.

csharp
using var sr = new StringReader("<Person><Name>Ada</Name><Age>30</Age></Person>");
var restoredXml = (Person)xml.Deserialize(sr)!;
Console.WriteLine($"{restoredXml.Name} {restoredXml.Age}");

Add schema validation or business-rule validation after deserialization if data quality is critical.

Testing During Serializer Migration

Migration should include:

  • round-trip tests for new serializer
  • fixtures with old payloads
  • malformed payload rejection tests
  • cross-version compatibility tests

These tests catch silent contract drift and help prevent production data corruption.

Common Pitfalls

A common mistake is assuming serializer replacement is purely syntactic. In reality, payload format and compatibility semantics change.

Another mistake is keeping BinaryFormatter in network or file-import paths because migration seems inconvenient.

A third mistake is ignoring versioning policy when switching to contract-driven serializers.

Teams also forget to test historical data migration and discover breakage only after deployment.

Summary

  • XmlSerializer is text-based and contract-oriented, while BinaryFormatter is legacy binary and obsolete.
  • Security concerns make BinaryFormatter unsuitable for modern deserialization scenarios.
  • Contract-based serializers are easier to evolve, audit, and interoperate with.
  • Benchmark safe modern serializers before making performance decisions.
  • Plan migrations in phases with compatibility and regression tests.

Course illustration
Course illustration

All Rights Reserved.