In c#, Serialization is a process of converting an object into a stream of bytes to store it in memory or database or a file. The main purpose of serialization is to save the state of an object to recreate it whenever we require it, 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#.
Generally, if we serialize an object into a stream, 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 you want to serialize a particular object like class, you need to apply Serializable
attribute on it. If we don’t want to serialize a particular field in our class, we need to apply the NonSerialized
attribute.
Following is a simple example of serializing the class in c#.
If you observe the above code, we are serializing UserDetails class by adding Serializable
attribute except for location field that’s the reason we added NonSerialized
attribute.
Following is the example of serializing the class and storing it in a file using binary serialization in c#.
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 the UserDetails class and store it in the “Test.txt” file in the D drive and return the result below.
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.