Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# object serialization
Object serialization in C# is the process of converting an object into a stream of bytes for storage or transmission. The serialized data can be saved to files, databases, or sent over a network, and later deserialized back into objects.
C# provides several approaches for serialization, including binary serialization, XML serialization, and JSON serialization. Binary serialization preserves the complete object state and type information.
Syntax
For binary serialization using BinaryFormatter −
[Serializable]
public class ClassName {
// class members
}
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, objectInstance);
For deserialization −
ClassName obj = (ClassName)formatter.Deserialize(stream);
Using Binary Serialization
To serialize an object using BinaryFormatter, the class must be marked with the [Serializable] attribute. Here's a complete example −
Example
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Employee {
public int id;
public string name;
public int salary;
public Employee(int id, string name, int salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public void Display() {
Console.WriteLine($"ID: {id}, Name: {name}, Salary: {salary}");
}
}
public class SerializationExample {
public static void Main() {
// Serialization
Employee emp = new Employee(001, "Jim", 30000);
FileStream fStream = new FileStream("employee.dat", FileMode.Create);
BinaryFormatter bFormat = new BinaryFormatter();
bFormat.Serialize(fStream, emp);
fStream.Close();
Console.WriteLine("Employee object serialized successfully.");
// Deserialization
FileStream fStreamRead = new FileStream("employee.dat", FileMode.Open);
Employee deserializedEmp = (Employee)bFormat.Deserialize(fStreamRead);
fStreamRead.Close();
Console.WriteLine("Deserialized Employee:");
deserializedEmp.Display();
}
}
The output of the above code is −
Employee object serialized successfully. Deserialized Employee: ID: 1, Name: Jim, Salary: 30000
Using JSON Serialization
Modern applications often prefer JSON serialization using System.Text.Json for better interoperability −
Example
using System;
using System.IO;
using System.Text.Json;
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Person() { }
public Person(int id, string name, int age) {
Id = id;
Name = name;
Age = age;
}
}
public class JsonSerializationExample {
public static void Main() {
Person person = new Person(1, "Alice", 25);
// Serialize to JSON
string jsonString = JsonSerializer.Serialize(person);
Console.WriteLine("Serialized JSON:");
Console.WriteLine(jsonString);
// Save to file
File.WriteAllText("person.json", jsonString);
// Deserialize from JSON
string jsonFromFile = File.ReadAllText("person.json");
Person deserializedPerson = JsonSerializer.Deserialize<Person>(jsonFromFile);
Console.WriteLine("\nDeserialized Person:");
Console.WriteLine($"ID: {deserializedPerson.Id}, Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
}
}
The output of the above code is −
Serialized JSON:
{"Id":1,"Name":"Alice","Age":25}
Deserialized Person:
ID: 1, Name: Alice, Age: 25
Comparison of Serialization Methods
| Method | Advantages | Disadvantages |
|---|---|---|
| Binary Serialization | Compact size, preserves exact object state | Platform-specific, not human-readable |
| JSON Serialization | Human-readable, cross-platform, lightweight | Larger size, limited type support |
| XML Serialization | Self-describing, cross-platform | Verbose, slower performance |
Key Rules
-
For binary serialization, classes must be marked with
[Serializable]attribute. -
Fields marked with
[NonSerialized]are excluded from serialization. -
JSON serialization works with public properties by default.
-
Always close file streams after serialization/deserialization operations.
Conclusion
Object serialization in C# converts objects to byte streams for storage or transmission. Binary serialization preserves complete object state but is platform-specific, while JSON serialization offers cross-platform compatibility and human readability. Choose the appropriate method based on your application's requirements for performance, compatibility, and data format.
