ProgrammingBackend Developer / VB.NET Developer

What methods are used for serialization and deserialization of objects in Visual Basic .NET, when should each method be used, and what pitfalls should be considered?

Pass interviews with Hintsage AI assistant

Answer.

In VB.NET, object serialization can be implemented in several ways using standard .NET serializers (BinaryFormatter, XmlSerializer, DataContractSerializer, JsonSerializer).

When to use:

  • BinaryFormatter — deprecated, not recommended for security reasons.
  • XmlSerializer — convenient for data exchange with external programs and for storing settings.
  • DataContractSerializer — suitable for serializing complex objects and interacting with WCF.
  • JsonSerializer (System.Text.Json or Newtonsoft.Json) — for modern web APIs and cross-language interactions.

Nuances:

  • Public fields and properties are serialized by default, private ones are not.
  • The serializable class must have a default constructor.
  • Exceptions may occur when serializing objects with circular references or non-serializable members.

Code example with XmlSerializer:

<Serializable()> Public Class Person Public Property Name As String Public Property Age As Integer End Class Dim p As New Person With {.Name = "Ivan", .Age = 30} Dim serializer As New Xml.Serialization.XmlSerializer(GetType(Person)) Using stream As New IO.FileStream("person.xml", IO.FileMode.Create) serializer.Serialize(stream, p) End Using

Trick question.

Can an object that contains properties with types not marked as serializable be serialized? What will happen?

Answer: If the class contains members (properties/fields) of types not marked as serializable, serialization will fail with an error. For example, an object with a field of type FileStream cannot be serialized using XmlSerializer — an exception will occur since this type does not support serialization.

Examples of real errors due to lack of knowledge of the topic nuances.


Story

Serialization error due to private constructor: During data migration, a developer attempted to serialize a class with only a private constructor. As a result, serialization failed with an error and the migration process was interrupted.


Story

Circular references: In the project, XmlSerializer was used for serialization, but there were circular references between objects. Serialization led to StackOverflowException and unhandled service failures.


Story

Accidental data loss: In a complex object serialized through JsonSerializer, a member was accidentally marked with [JsonIgnore], leading to the loss of part of the data during transmission, and subsequent deserialization lost important parameters of the object.