C# Serialization

In c#, Serialization is a process of converting an object into a stream of bytes to store it in memory or database or in a file. The main purpose of serialization is to save the state of an object to recreate it whenever we required and we can send an object to other applications either by using web or rest services.

 

The following diagram will illustrate the process of serialization in c#.

 

C# Serialization Process Flow Diagram

 

Generally, if we serialize an object into a stream, then it will carry the information about that particular object type such as its version, assembly name, etc. along with the data.

 

In c#, we can serialize the objects either by using binary or XML serialization. In binary serialization, all the members will be serialized and performance is better but XML serialization will provide better code readability and greater flexibility for object sharing.

 

If we want to serialize a particular object like class, then we need to apply Serializable attribute on it. In case, if we don’t want to serialize a particular field in our class, then we need to apply the NonSerialized attribute.

 

Following is the simple example of serializing the class in c#.

 

[Serializable()]

public class UserDetails

{

    public int userId { get; set; }

    public string userName { get; set; }

    // A field that is not serialized

    [NonSerialized()]

    public string location { get; set; }

    public UserDetails()

    {

        userId = 1;

        userName = "Suresh";

        location = "Hyderabad";

    }

}

If you observe the above code, we are serializing UserDetails class by adding Serializable attribute except location field that’s the reason we added NonSerialized attribute.

C# Serialization Example

Following is the example of serializing the class and storing it in a file using binary serialization in c#.

 

using System;

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            UserDetails ud = new UserDetails(1, "Suresh", "Hyderabad");

            Console.WriteLine("Before serialization the object contains: ");

            ud.GetDetails();

            string fpath = @"D:\Test.txt";

            // Check if file exists

            if (File.Exists(fpath))

            {

                File.Delete(fpath);

            }

            //Opens a file and serializes the object into it in binary format.

            Stream stream = File.Open(fpath, FileMode.Create);

            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(stream, ud);

            stream.Close();

            Console.WriteLine("\nSerialization Successful");

            Console.ReadLine();

        }

    }

    [Serializable()]

    public class UserDetails

    {

        public int userId { get; set; }

        public string userName { get; set; }

        public string location { get; set; }

        public UserDetails(int id, string name, string place)

        {

            userId = id;

            userName = name;

            location = place;

        }

        public void GetDetails()

        {

            Console.WriteLine("UserId: {0}", userId);

            Console.WriteLine("UserName: {0}", userName);

            Console.WriteLine("Location: {0}", location);

        }

    }

}

If you observe the above example, we are serializing the class called “UserDetails” using binary serialization and storing it in a file.

 

When we execute the above example, it will serialize UserDetails class and stored in “Test.txt” file in D drive and return the result like as shown below.

 

C# Serialization Example Result

 

This is how we can serialize the objects in c# based on our requirements. In the next chapter, we will learn how to use the deserialization process to convert the stream of bytes to object with examples.

 
 
 

Topics Covered