How to serialize and deserialize objects in C#?

In C#, serialization and deserialization of objects can be achieved by utilizing the DataContractSerializer class in the System.Runtime.Serialization namespace.

Example code for serializing objects:

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

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

class Program
{
    static void Main()
    {
        Person person = new Person { Name = "Alice", Age = 30 };

        DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
        using (FileStream stream = new FileStream("person.xml", FileMode.Create))
        {
            serializer.WriteObject(stream, person);
        }
    }
}

Example code for deserializing objects:

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

class Program
{
    static void Main()
    {
        DataContractSerializer serializer = new DataContractSerializer(typeof(Person));
        using (FileStream stream = new FileStream("person.xml", FileMode.Open))
        {
            Person person = (Person)serializer.ReadObject(stream);
            Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
        }
    }
}

In the code above, the Person class uses DataContract and DataMember attributes to denote the properties that need to be serialized, and then uses the DataContractSerializer class to serialize the object into an XML file or deserialize it from an XML file into an object.

bannerAds