Serializable Attribute in C#: What It Is and How It Works
[Serializable] attribute in C# marks a class so its objects can be converted into a format that can be saved or sent, called serialization. This allows the object data to be stored or transferred and later restored back into an object.How It Works
Imagine you have a toy robot that you want to pack into a box to send to a friend. Serialization is like taking the robot apart carefully and packing all its parts into the box. The [Serializable] attribute tells C# that the class's objects can be taken apart (converted) into a format that can be saved or sent, such as a file or over the internet.
When you want to use the robot again, you unpack the box and put the parts back together. This process is called deserialization. Without the [Serializable] attribute, C# won't allow the object to be packed and unpacked this way, because it doesn't know if it's safe or possible to do so.
Example
This example shows a simple class marked with [Serializable]. We create an object, serialize it to a file, then read it back (deserialize) and print its data.
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 p = new Person { Name = "Alice", Age = 30 }; // Serialize object to file using (FileStream fs = new FileStream("person.dat", FileMode.Create)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, p); } // Deserialize object from file Person p2; using (FileStream fs = new FileStream("person.dat", FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); p2 = (Person)formatter.Deserialize(fs); } Console.WriteLine($"Name: {p2.Name}, Age: {p2.Age}"); } }
When to Use
Use the [Serializable] attribute when you need to save an object's state to a file, send it over a network, or store it in memory for later use. For example, saving user settings, caching data, or communicating between programs.
It is important when you want to preserve the exact data of an object and restore it later without losing information. However, not all classes should be serializable, especially if they contain sensitive data or resources like open files.
Key Points
- The
[Serializable]attribute enables object serialization in C#. - Serialization converts an object into a format for storage or transfer.
- Deserialization restores the object from the stored format.
- Not all classes should be serializable; consider security and resource management.