Wednesday, April 21, 2010

Lesson 6 - Partial Serialization

Partial Serialization


When performing serialization, you can make it possible to save only some parts of the class. When creating a class, you can specify what fields would be serialized and which ones would not be. To specify that a member cannot be saved, you can mark it with the [NonSerialized] attribute. Here is an example:

[Serializable]
public class Car
{
public string Make;
public string Model;

// Because the value of a car can change,
// there is no reason to save it
[NonSerialized]
public decimal Value;
public uint Year;
public byte Color;
}

After creating the class, you can declare a variable of it and serialize it, using either the binary or the SOAP approach. Here is an example:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Car
{
public string Make;
public string Model;

// Because the value of a car can change,
// there is no reason to save it
[NonSerialized]
public decimal Value;
public uint Year;
public byte Color;
}

public class Exercise
{
static int Main(string[] args)
{
var vehicle = new Car();

vehicle.Make = "Lexus";
vehicle.Model = "LS";
vehicle.Year = 2007;
vehicle.Color = 4;
vehicle.Value = 28640M;

var stmCar = new FileStream("Car1.car", FileMode.Create);
var bfmCar = new BinaryFormatter();

bfmCar.Serialize(stmCar, vehicle);


return 0;
}
}
You can then retrieve the object and its values, using any of the techniques we learned earlier. Here is an example:

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Car
{
public string Make;
public string Model;

// Because the value of a car can change,
// there is no reason to save it
[NonSerialized]
public decimal Value;
public uint Year;
public byte Color;
}

public class Exercise
{
static int Main(string[] args)
{
var stmCar = new FileStream("Car1.car", FileMode.Open);
var bfmCar = new BinaryFormatter();
var vehicle = (Car)bfmCar.Deserialize(stmCar);

Console.WriteLine("Car Information");
Console.WriteLine("Make: {0}", vehicle.Make);
Console.WriteLine("Model: {0}", vehicle.Model);
Console.WriteLine("Year: {0}", vehicle.Year);
Console.Write("Color: ");
switch (vehicle.Color)
{
case 1:
Console.WriteLine("Black");
break;
case 2:
Console.WriteLine("Gray");
break;
case 3:
Console.WriteLine("White");
break;
case 4:
Console.WriteLine("Red");
break;
case 5:
Console.WriteLine("Blue");
break;
}
Console.WriteLine("Value: {0}\n", vehicle.Value);

return 0;
}
}
This would produce:

Car Information
Make: Lexus
Model: LS
Year: 2007
Color: Red
Value: 0

Press any key to continue . . .
Notice that the value of the Value field was not saved: it holds the default value of its data type. This indicates that, you can assign a value a [NonSerialized] field and save the object. The value of that field would not be saved but the compiler would not throw an exception.

No comments:

Post a Comment