DataContractSerializer Class
Serializes and deserializes an instance of a type into an XML stream or document using a supplied data contract. The DataContractSerializer provides a flexible, high-performance way to transform objects to XML and back, supporting complex types, collections, and inheritance.
Syntax
public class DataContractSerializer : XmlObjectSerializer
{
public DataContractSerializer(Type type);
public DataContractSerializer(Type type, IEnumerable<Type> knownTypes);
public DataContractSerializer(Type type, string rootName, string rootNamespace);
public DataContractSerializer(Type type, IEnumerable<Type> knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, IDataContractSurrogate dataContractSurrogate);
// … properties and methods …
}
Remarks
The serializer works based on data contracts—explicit declarations of how a type's data is represented in XML. When no data contract is defined, the serializer infers one from the public members of the type.
- Supports preserveObjectReferences to handle circular references.
- Allows custom IDataContractSurrogate implementations for advanced scenarios.
- Optimized for performance; frequently used in WCF services.
Examples
Serialize an object to a file and then deserialize it back.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
[DataContract]
public class Person
{
[DataMember] public string FirstName { get; set; }
[DataMember] public string LastName { get; set; }
[DataMember] public int Age { get; set; }
}
class Program
{
static void Main()
{
var person = new Person { FirstName = "Ada", LastName = "Lovelace", Age = 36 };
var serializer = new DataContractSerializer(typeof(Person));
// Serialize
using (var stream = new FileStream("person.xml", FileMode.Create))
using (var writer = XmlDictionaryWriter.CreateTextWriter(stream, System.Text.Encoding.UTF8))
{
serializer.WriteObject(writer, person);
}
// Deserialize
Person deserialized;
using (var stream = new FileStream("person.xml", FileMode.Open))
using (var reader = XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max))
{
deserialized = (Person)serializer.ReadObject(reader);
}
Console.WriteLine($\"{deserialized.FirstName} {deserialized.LastName}, Age {deserialized.Age}\");
}
}
Properties
- KnownTypes – Gets the collection of types that may be present in the object graph.
- PreserveObjectReferences – Indicates whether object reference preservation is enabled.
- DataContractSurrogate – Gets the surrogate used during serialization.
Methods
- WriteObject(XmlWriter, Object) – Serializes the supplied object.
- ReadObject(XmlReader) – Deserializes the XML content into an object.
- IsStartObject(XmlReader) – Determines whether the reader is positioned at the start of a serialized object.