Namespace: System.Runtime.Serialization
Assembly: System.Runtime.Serialization.dll

NetDataContractSerializer Class

Serializes and deserializes an object graph using the Data Contract Serialization format.

This class supports the serialization of any public or private object graph. The Data Contract Serializer does not rely on attributes to determine which members to serialize, but rather relies on the object graph structure.

Inheritance Hierarchy

System.Object
  System.Runtime.Serialization.NetDataContractSerializer

Syntax

Visual Basic

Public Class NetDataContractSerializer
    Inherits XmlObjectSerializer

C#

public class NetDataContractSerializer : XmlObjectSerializer

Constructors

Methods

Remarks

The NetDataContractSerializer serializes and deserializes objects using the Data Contract Serialization format. This format is based on the XML Schema Definition (XSD) specification and is designed to interoperate with services written in other languages.

Unlike the DataContractSerializer, the NetDataContractSerializer serializes the actual .NET Framework type names and member names, rather than relying on data contract names. This means that the serialized output is specific to .NET Framework clients and cannot be easily consumed by clients written in other languages.

The NetDataContractSerializer can serialize any public or private object graph. It does not require attributes to determine which members to serialize; it serializes all members that are part of the object's structure.

Example

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

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

public class Example
{
    public static void Main(string[] args)
    {
        Person person = new Person { Name = "Alice", Age = 30 };

        NetDataContractSerializer serializer = new NetDataContractSerializer();

        using (MemoryStream ms = new MemoryStream())
        {
            using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms))
            {
                serializer.WriteObject(writer, person);
                writer.Flush();

                ms.Position = 0; // Reset stream position for reading

                // Deserialize the object
                Person deserializedPerson = (Person)serializer.ReadObject(XmlDictionaryReader.CreateTextReader(ms, new XmlDictionaryReaderQuotas()));

                Console.WriteLine($"Deserialized Person: Name={deserializedPerson.Name}, Age={deserializedPerson.Age}");
            }
        }
    }
}