C Sharp Serialization

C# Serialization

To convert an object into a byte stream to be saved to memory, file or database, the process of serialization is used in C#. In remote applications, it is used internally.

C# SerializableAttribute:

The SerializableAttribute attribute is applied to the type, to serialize the object. Without this, the SerializationException exception will be thrown at runtime.


using System;  
using System.IO;  
using System.Runtime.Serialization.Formatters.Binary;  
class Employee  
    int ID;  
    string Name;  
    public Employee(int ID, string Name)  
        this.ID = ID;  
        this.Name = Name;  
public class Example  
    public static void Main(string[] args)  
        FileStream str = new FileStream("d:\\file.txt", FileMode.OpenOrCreate);  
        BinaryFormatter frmtr = new BinaryFormatter();  
        Employee emp = new Employee(10, "Vishal Gupta");  
        frmtr.Serialize(str, emp);  



In the above example, we are using the serialization in C# to serialize the object of the “Employee” class. To serialize the object, the BinaryFormatter.Serialize(stream, reference) method is used. The serialized data is finally stored in the file, which can be retrieved by performing the process of Deserialization.

Please follow and like us:
Content Protection by DMCA.com