In the C#, Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to a memory file or database such as XML or binary format.
In the c# programming language reverse process of serialization is called deserialization. In simple words serialization in C# programming language is a process of storing the object instance to a persistent storage
C# SerializableAttribute
To serialize the object, we need to apply SerializableAttribute attribute to the type. If you don't apply SerializableAttribute attribute to the type, SerializationException exception is thrown at runtime.
C# Serialization example
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
public class Student
{
int rollNumber;
string fullName;
public Student(int rollNumber, string fullName)
{
this.rollNumber= rollNumber;
this.fullName= fullName;
}
}
public class SerializeExample
{
public static void Main(string[] args) { FileStream stream = new FileStream("D:\\test.txt",FileMode.OpenOrCreate);
BinaryFormatter formatter=new BinaryFormatter();
Student objStudent= new Student(2, "Sylvia"); formatter.Serialize(stream,objStudent);
stream.Close(); }
}