สำหรับการทำ Serialization ของออบเจกต์ ให้ใช้เมธอด BinaryFormatter.Serialize(stream, reference) ตัวอย่างโค้ดด้านล่างแสดงการ serialize ออบเจกต์แบบง่าย
กำหนด Constructor:
public Employee(int id, string name, int salary)
{
this.id = id;
this.name = name;
this.salary = salary;
}
ตั้งค่า FileStream:
FileStream fStream = new FileStream("d:\\new.txt", FileMode.OpenOrCreate);
BinaryFormatter bFormat = new BinaryFormatter();
สร้างออบเจกต์ Employee และทำ Serialization:
Employee emp = new Employee(001, "Jim", 30000); bFormat.Serialize(fStream, emp);