Serialization is a crucial concept in C# programming. It's the process of converting complex data structures or objects into a format that can be easily stored or transmitted. This guide will explore C# serialization, its types, and practical applications.
Serialization transforms objects into a stream of bytes. This allows you to:
Deserialization is the reverse process, reconstructing objects from serialized data.
Binary serialization converts objects to a compact binary format. It's fast and efficient but not human-readable.
XML serialization creates human-readable XML representations of objects. It's versatile but can be slower than binary serialization.
JSON serialization produces lightweight, readable JSON data. It's widely used in web applications and APIs.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "John Doe", Age = 30 };
// Serialize
using (FileStream fs = new FileStream("person.dat", FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, person);
}
// Deserialize
using (FileStream fs = new FileStream("person.dat", FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
Person deserializedPerson = (Person)formatter.Deserialize(fs);
Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
}
}
}
using System;
using System.Text.Json;
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
static void Main()
{
Person person = new Person { Name = "Jane Smith", Age = 25 };
// Serialize
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine(jsonString);
// Deserialize
Person deserializedPerson = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
}
}
[Serializable]
attribute for classes you want to serialize.To deepen your understanding of C# serialization, explore these related topics:
Mastering serialization in C# opens up possibilities for data persistence and inter-process communication. It's an essential skill for building robust and scalable applications.