What is serialization? When to use? How to implement in C#?

Question:

[Serializable]
public class Pessoa
{
    public string Nome { get; set; }
    public string Cpf { get; set; }
}
  • Is there only one type of serialization ?
  • What are the alternatives for not needing to serialize an object?

Answer:

Serialization: What is it?

In computer science, in the context of data storage and transmission, serialization is the process of saving or transliterating an object into another in a storage medium (such as a computer file or a memory buffer) or transmitting it over a network connection, either in binary form or in text format such as XML or JSON. This series of bytes can be used to recreate an object with the same internal state as the original.

Source: http://pt.wikipedia.org/wiki/Serializa%C3%A7%C3%A3o (adapted)

Is there only one type of serialization?

No. There are several types of serialization, the difference being the final data representation format. For example, using the Json method from the Newtonsoft.Json library, you will have a JSON serialization. Using the System.Xml.Serialization.XmlSerializer object, you can convert (or serialize) an object to XML format.

in JSON

var objeto = new { nome = "Nome", valor = "Valor" };
return Json(objeto, JsonRequestBehavior.AllowGet);

Result

{ 'nome': 'Nome', 'valor': 'Valor' }

In XML

I will use your class:

[Serializable]
public class Pessoa
{
    public string Nome { get; set; }
    public string Cpf { get; set; }
}

Use:

var pessoa = new Pessoa { Nome = "Nome", Cpf = "123.456.789-01" };
XmlSerializer x = new XmlSerializer(pessoa.GetType());
x.Serialize(Console.Out, pessoa);

Result

<?xml version="1.0" encoding="IBM437"?>
 <pessoa xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3
 .org/2001/XMLSchema">
    <Nome>Nome</Nome>
    <Cpf>123.456.789-01</Cpf>
</pessoa>

How to implement in C#?

Serialization is already implemented in C# for different formats. Serialization should be seen first as a concept, then as a language feature.

You can even implement your serialization to whatever format you like, but ideally, use ready-made components to avoid extra work.

Scroll to Top