Serialization and Class Hierarchies

When you apply the Serializable attribute to a class, it affects only that class—it doesn’t make any derived classes serializable, because the Inherited property of the AttributeUsage attribute applied on the Serializable attribute is set to false. For example, if you derive MyClass from MyBaseClass, MyClass isn’t serializable:

    [Serializable]
    public class MyBaseClass
    {}
    public class MyClass : MyBaseClass
    {}

At first glance this may appear awkward, but it does make design sense: MyBaseClass has no way of knowing whether its subclasses will have non-serializable members, so it would be wrong for them to automatically inherit the serializable status. If you design a class hierarchy and you want to support serialization of any type in the hierarchy, be sure to mark each level with the Serializable attribute:

    [Serializable]
    public class MyBaseClass

    {}
    [Serializable]
    public class MyClass : MyBaseClass
    {}
    [Serializable]
    public class MyOtherClass : MyClass
    {}

Custom Serialization and Base Classes

If any of the classes in the hierarchy implements ISerializable, there are a few design guidelines you have to follow to allow subclasses to provide their own custom serialization and to correctly manage the custom serialization of the base classes:

  • Only the topmost base class that uses custom serialization needs to derive from ISerializable.

  • When using implicit interface implementation, a base class must define its GetObjectData() method as virtual to allow subclasses ...

Get Programming .NET Components, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.