How to register a global hotkey for your application in C#

How to register a global hotkey for your application in C#

Register a hotkey for your application that can be triggered even if your form is minimized and does not have focus. More »

How to download a file in C# (progressbar and download speed)

How to download a file in C# (progressbar and download speed)

Learn how to download files in C# while displaying the percentage and the download speed. More »

UDP hole punching implementation in C#

UDP hole punching implementation in C#

Learn how to implement UDP hole punching so you can make your clients life a lot easier by not forcing them to open ports on their end. More »

 

Serialize an object to string and from string back to object

Serialization enables us to store or transmit data structures or objects. This can be done by converting the data to a textual representation when storing or transmitting them which also allows us to recreate the original object using the stored information.

Lets create a dummy class called Person, that will hold some basic information.

Keep in mind that your class needs to have a parameterless constructor in order to be serialized or else you will get an InvalidOperationException exception (cannot be serialized because it does not have a parameterless constructor) if you try to serialize a class without one. Luckily you can just set it to private or internal so it won’t be accessible from other classes.

Now it is time to serialize our Person object.


At this point our serializedData variable will be holding the serialized data. This is what you will use when storing or transmitting your object somewhere. You can see below the contents of serializedData.

Now lets deserialize our data to recreate our Person object.

The deserializedPerson object will have exactly the same data as the object we serialized at the start.

Hopefully the above example helped you understand the basics on how to serialize and deserialize objects. If you have any questions feel free to ask in the comments below.

Share on FacebookTweet about this on TwitterShare on Google+Share on StumbleUponShare on LinkedInShare on RedditPin on PinterestShare on TumblrDigg thisPrint this pageEmail this to someone

One Response to Serialize an object to string and from string back to object

  1. Ramon E. Ritter says:

    Thank you very much! Your article was the most educational that I found and helped me a lot to understand how serialization/deserialization works.

Leave a Reply

Your email address will not be published. Required fields are marked *