Delving Deeper into Serialization with .NET - A Caution on Serialization and Inheritance
(Page 2 of 4 )
Now we have a serializable Shape class, but does the fact that Shape is serializable make ThreeDimensionalShape serializable as well? In other words, does a class inherit the ability to be serialized? To find out, let's write and run some code that attempts to serialize instances of both classes:
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
class InheritanceAndSerialization
{
public static void Main(string[] args)
{
// Create a ThreeDimensionalShape
ThreeDimensionalShape cylinder = new ThreeDimensionalShape(12.57, 3.14);
// Serialize cylinder
MemoryStream myStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(myStream, cylinder);
myStream.Close();
Console.WriteLine("Cylinder serialized.");
}
}
When we run the above code, we get a nasty error:
Unhandled Exception: System.Runtime.Serialization.SerializationException:Type ThreeDimensionalShape is not marked as Serializable.
...
So, no, a class that wants to be serialized must apply the Serializable attribute, even if its base class applies the attribute. If we modify the ThreeDimensionalShape class by applying the attribute, then the above code runs fine:
[Serializable]
public class ThreeDimensionalShape : Shape
{
...
}
Cylinder serialized.
Note that ThreeDimensionalShape does not have access to Shape's area field since we have it set as private. However, when a ThreeDimensionalShape is serialized, area is serialized too, and when the object is deserialized, all of the serializable internal data is restored. .NET handles all of this for us, so properly serializing child class instances is as simple as marking the child class as Serializable. .NET handles all of the work behind the scenes.
There is still one situation we haven't looked at, though: can a child class be serialized if its parent class isn't marked with the Serializable attribute? Remove the Serializable attribute from Shape and run the above code again:
Unhandled Exception: System.Runtime.Serialization.SerializationException:Type Shape in assembly _Serialization, Version=0.0.0.0, Culture=neutral is not marked as serializable.
...
No, it would appear that it's not possible to serialize an instance of a class whose parent class isn't serializable, even if the child class is itself serializable. .NET's serialization mechanisms work their magic only if we play by the rules, and the rules state that in order for instances of a class to be serializable, its base class must also be serializable. That said, however, it is still possible to serialize an instance of such a class, though the solution isn't pretty since .NET won't automatically do the work for us.
Next: ISerializable >>
More .NET Articles
More By Peyton McCullough