Serialization in VB.Net

Serialization in VB.NET is the process of converting an object's state into a binary or XML format that can be easily stored, transmitted, or persisted. Deserialization is the reverse process of reconstructing an object from its serialized form. This is often used for saving and loading objects to/from files, sending objects over networks, or caching.

Here's a detailed explanation with examples of object serialization in VB.NET using the built-in .NET Framework's BinaryFormatter for binary serialization and XmlSerializer for XML serialization:

Binary Serialization

Binary serialization involves converting an object into a binary format.

Serialization
Imports System.IO Imports System.Runtime.Serialization.Formatters.Binary <Serializable()> ' Mark the class as serializable Public Class Person Public Property Name As String Public Property Age As Integer End Class ' Serialize the object Dim person As New Person() With {.Name = "Alice", .Age = 30} Dim formatter As New BinaryFormatter() Using fs As New FileStream("person.bin", FileMode.Create) formatter.Serialize(fs, person) End Using
Deserialization
' Deserialize the object Using fs As New FileStream("person.bin", FileMode.Open) Dim deserializedPerson As Person = CType(formatter.Deserialize(fs), Person) Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}") End Using

XML Serialization

XML serialization involves converting an object into an XML format.

Serialization
Imports System.Xml.Serialization Public Class Person Public Property Name As String Public Property Age As Integer End Class ' Serialize the object Dim person As New Person() With {.Name = "Bob", .Age = 25} Dim serializer As New XmlSerializer(GetType(Person)) Using writer As New StreamWriter("person.xml") serializer.Serialize(writer, person) End Using
Deserialization
' Deserialize the object Using reader As New StreamReader("person.xml") Dim deserializedPerson As Person = CType(serializer.Deserialize(reader), Person) Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}") End Using

In both examples, we create a Person object, serialize it to a file, and then deserialize it back into a new object. The Serializable attribute is used for binary serialization to indicate that the class can be serialized.

Conclusion

Serialization is a useful technique for various scenarios, such as saving application state, sharing data between different applications, and sending data across networks. Binary serialization is more efficient but less human-readable, while XML serialization is human-readable and can be used for data interchange with other systems.