Delving Deeper into Serialization with .NET (Page 1 of 4 )
In "Serialization with .NET," we began by serializing a simple string. Then, we moved on to serializing custom types and examined how a class can participate in the serialization and deserialization processes using the OnSerializing, OnSerialized, OnDeserializing and OnDeserialized attributes. In this article, we'll continue to examine serialization with .NET.
Inheritance
So far, we've only serialized simple classes that don't inherit from anything besides Object. However, it's important to take note of the combination of serialization and inheritance. To experiment, let's create two classes, one of which will inherit from the other. The first will be Shape and will represent any sort of shape. It will have a private field named area with an associated property, Area. The second will be ThreeDimensionalShape and will represent a three-dimensional shape. It will have a private field named volume, with can be accessed through the property Volume. Here are the two classes:
using System;
public class Shape
{
private double area;
public Shape(double area)
{
this.area = area;
}
public double Area
{
get
{
return area;
}
}
}
public class ThreeDimensionalShape : Shape
{
private double volume;
public ThreeDimensionalShape(double area, double volume)
: base(area)
{
this.volume = volume;
}
public double Volume
{
get
{
return volume;
}
}
}
Now, let's apply the Serializable attribute to Shape so that it can be serialized:
[Serializable]
public class Shape
{
...
}
Next: A Caution on Serialization and Inheritance >>
More .NET Articles
More By Peyton McCullough