At some point in the development of most software applications, design decisions are made about how to store and retrieve application data. For example, if your application reads and writes to disk files, you need to make basic choices about how to represent the data on disk. In this column we want to look a bit at C# I/O issues, and in particular at a mechanism called serialization. Serialization is used to convert C# objects into bytestreams, in a standardized way, so that those objects can be saved to disk or sent across a network.

The Need for Serialization
Let’s start by considering a couple of examples. The first one writes a floating-point value to a text file and then reads it back:
using System;
using System.IO;
public class SerialDemo1 {
public static void Main() {
// write double value to text file
double d1 = 0.1 + 0.1 + 0.1;
StreamWriter sw =
new StreamWriter(”out”, false);
sw.WriteLine(d1);
sw.Close();
// read double value back from text file
StreamReader sr = new
StreamReader(”out”);
string ln = sr.ReadLine();
double d2 = Double.Parse(ln);
sr.Close();
// compare values
if (d1 != d2) {
Console.WriteLine(”d1 != d2″);
Console.WriteLine(”difference = ” +
(d1 - d2));
}
}
}
When this program is run, the result is:
d1 != d2
difference = 5.55111512312578E-17

For some reason, our attempt to store a floating value in a text file fails. If we know much about floating-point, we may not be surprised, given that many decimal values have no exact representation in binary. For example, the common value 0.1 is the sum of an infinite series of binary fractions. Somehow our initial value got changed a bit, due to roundoff factors and so forth.

Download pdf Working with C# Serialization