Serialized Object Persistence and formatters

0

In .NET, object serialization is the process of converting an object into a format that can be stored or transmitted, such as binary or XML. Serialized object persistence is the ability to save a serialized object to a storage medium, such as a file or a database, and later retrieve and deserialize it.

Formatters are classes that are used to perform serialization and deserialization of objects. The .NET Framework provides two main formatters: BinaryFormatter and XmlSerializer. The BinaryFormatter class is used to serialize objects into binary format, while the XmlSerializer class is used to serialize objects into XML format.

Here is an example of how to use the BinaryFormatter class to persist a serialized object to a file:

csharp
using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; [Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main(string[] args) { // Create a new Person object Person person = new Person { Name = "John Smith", Age = 30 }; // Serialize the object to a file using BinaryFormatter using (FileStream stream = new FileStream("person.bin", FileMode.Create)) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, person); } // Deserialize the object from the file using (FileStream stream = new FileStream("person.bin", FileMode.Open)) { BinaryFormatter formatter = new BinaryFormatter(); Person deserializedPerson = (Person)formatter.Deserialize(stream); Console.WriteLine("Name: {0}, Age: {1}", deserializedPerson.Name, deserializedPerson.Age); } } }

In this example, we create a simple Person class with two properties: Name and Age. The [Serializable] attribute is applied to the class to indicate that it can be serialized. We then create a new Person object and serialize it to a file named "person.bin" using BinaryFormatter.


To deserialize the object, we create a new FileStream object and pass it to a new instance of BinaryFormatter. We then call the Deserialize method to retrieve the object from the file. The deserialized object is cast to the Person type and printed to the console.


Note that the [Serializable] attribute must be applied to any class that is intended to be serialized using BinaryFormatter. Additionally, any fields or properties that should not be serialized should be marked with the [NonSerialized] attribute.


In summary, object serialization and deserialization is a powerful feature in .NET that allows objects to be stored or transmitted in a compact format. Formatters, such as BinaryFormatter and XmlSerializer, provide a convenient way to perform serialization and deserialization of objects. Serialized object persistence allows objects to be saved to a storage medium and later retrieved and deserialized.

Tags

Post a Comment

0Comments
Post a Comment (0)