List, serialize. In C# programs we often need to read and write data from the disk. A List can be serialized—here we serialize (to a file) a List of objects.
Serialize notes. The next time the program runs, we get this List straight from the disk. We see an example of BinaryFormatter and its Serialize methods.
Example code. We see a "Lizard" class in C# code. This is the class we are going to serialize. The program includes the relevant namespaces at the top.
Here We see a class called Lizard, and it has 3 properties. These properties are publicly accessible.
Tip You can type "s" to write a List of classes to a file, and "r" to read in that same List.
Tip 2 When you press "s," a new List of Lizard objects is created. Five different Lizard objects are instantiated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable()]
public class Lizard
{
public string Type { get; set; }
public int Number { get; set; }
public bool Healthy { get; set; }
public Lizard(string t, int n, bool h)
{
Type = t;
Number = n;
Healthy = h;
}
}
class Program
{
static void Main()
{
while(true)
{
Console.WriteLine("s=serialize, r=read:");
switch (Console.ReadLine())
{
case "s":
var lizards1 = new List<Lizard>();
lizards1.Add(new Lizard("Thorny devil", 1, true));
lizards1.Add(new Lizard("Casquehead lizard", 0, false));
lizards1.Add(new Lizard("Green iguana", 4, true));
lizards1.Add(new Lizard("Blotched blue-tongue lizard", 0, false));
lizards1.Add(new Lizard("Gila monster", 1, false));
try
{
using (Stream stream = File.Open("data.bin", FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, lizards1);
}
}
catch (IOException)
{
}
break;
case "r":
try
{
using (Stream stream = File.Open("data.bin", FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
var lizards2 = (List<Lizard>)bin.Deserialize(stream);
foreach (Lizard lizard in lizards2)
{
Console.WriteLine("{0}, {1}, {2}", lizard.Type, lizard.Number, lizard.Healthy);
}
}
}
catch (IOException)
{
}
break;
}
}
}
}s=serialize, r=read:
s
s=serialize, r=read:
r
Thorny devil, 1, True
Casquehead lizard, 0, False
Green iguana, 4, True
Blotched blue-tongue lizard, 0, False
Gila monster, 1, False
s=serialize, r=read:
Code notes. We call the Serialize method on the BinaryFormatter instance. This Serialize method receives the stream you want to write to, and also the object itself.
Detail We wrap the file IO code in a try-catch block. This is important because file IO frequently throws.
And The Stream is wrapped in a using block. The File.Open call attempts to open the new file for writing.
Deserialize. To deserialize, the code uses a Stream wrapped in a using-block. A new BinaryFormatter object is created, and it is used to get a new List.
Note The Deserialize method, which accepts the Stream as a parameter, is slow but also powerful.
Finally We write the List of Lizards it has read in from the file to the screen in a foreach-loop.
Properties. It is important to use properties in this sort of serialization code. Properties have metadata in the compiled code, which enables sophisticated logic.
JSON. A modern solution to serialization is JSON, which is included in .NET 5 and later versions. JSON support has been optimized in .NET 5.
A summary. We took a List generic instance with five objects in it, and serialized it efficiently. And we employed the "using" statement for optimal clarity.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 20, 2024 (edit).