tags:

views:

1241

answers:

3

If something inherits from a Serializable class, is the child class still Serializable?

A: 

That would be a yes.

Chris Lively
Except that it doesn't... (see below)
Marc Gravell
Except that it does. You even said so about the ISerializable interface.
Chris Lively
Which is only *one* of the ways in which something can be considered serializable. Now: only the OP knows whether their class is [Serializable], ISerializable, [DataContract], IXmlSerializable, etc - but a sweeping "yes" is completely incorrect.
Marc Gravell
Yes, it is only one way to be considered serializable. However, it is the only way that covers the original question about inheritance.
Chris Lively
A: 

Be careful if you implement ISerializable! You have to override its methods and, after you're done serializing your properties, you must call the base class' implementations!

Will
I'll keep a heads up for it. Thank you.
Joe Morgan
+6  A: 

It depends what you mean be serializable. If you mean the CLI marker (i.e. the [Serializable] attribute), then this is not inherited (proof below). You must explicitly mark each derived class as [Serializable]. If, however, you mean the ISerializable interface, then yes: interface implementations are inherited, but you need to be careful - for example by using a virtual method so that derived classes can contribute their data to the serialization.

using System;
class Program
{
    static void Main()
    {
        Console.WriteLine(typeof(Foo).IsSerializable); // shows True
        Console.WriteLine(typeof(Bar).IsSerializable); // shows False
    }
}
[Serializable]
class Foo {}
class Bar : Foo {}
Marc Gravell
Attributes, by their nature, are not inherited. Also, a class can not be considered to inherit from an attribute. Ergo, attributes have nothing to do with the OP's question.
Chris Lively
Sorry, but you are wrong. Attributes *do* relate to the question; the [Serializable] attribute is one of those that the compiler handles differently: it uses this to set the "serializable" flag on the CLI class (if you check the IL, it actually throws away the attribute at this point).
Marc Gravell
Equally, I never said anything about the class inheriting from an attribute - although actually, since attributes *are* classes, and attributes can inherit from each-other, an attribute class very-much inherits from an attribute...
Marc Gravell