C# language: Data serialization

Hi, today about the serialization in the previous lesson we was saving down a line by line the data that could have been saved in a much simpler way, eg save the entire data object to the stream for this serialization.

We are not limited to writing data line by line, we can save and copy entire objects using serialization! Only always above the class name you have to add the [Serializable] line so that the compiler knows that this class is intended for serialization.

Let’s get to the point, let’s create a simple console application and a class called SerializableClass, and just save there sample data, which we will serialize later, of course you can not forget about the [Serializable] declaration above the class name. The whole SerializableClass class looks like this:

Then add the following to the “Main” function this code:

I already explain what is going on:

First, we create a class SerializableClass object and assign some values to its fields, then we create a BinaryFormatter object using this object, we change the data that we previously introduced into the stream, then open the serialization.txt file (this file must be created manually on the desktop) and set its access to data storage.

Then, using the binFormat object, we serialize the data in the first argument we specify to which file we want to save this data and in the second argument we specify what data we want to save and close the file.

If we will open the file now , then the compiler encoded it into the appropriate string, but the data is there as we put it there, to prove it we will make the file file deserializ, that is, read the data from the file.

Below the code after closing the file after entering the number 1, we call the LoadData() method, which deserializes the file, here is its code:

First, we open the file to read, the same to which we saved the data of course, then we create a class BinaryFormatter object.

And we deserialize the data by creating the object of the SerializableClass class and projecting it to the Deserialize() method giving in the argument which file to read then we display this data on the screen, the values that we display should be the same as we introduced them at the beginning. And finally, we close the file.

This content also you can find on my steemit blog: https://steemit.com/programming/@slawas/c-language-data-serialization

And on medium: https://medium.com/@sawomirkowalski/c-language-data-serialization-2b3783473932

That’s all in short when it comes to serialization and deserialization of data, it’s very useful to have a few lines to save the whole object and probably not too hard, see you!

If that post was useful for you share it with your friends :)

Post a comment

Notify about