If something inherits from a Serializable class, is the child class still Serializable?
Except that it doesn't... (see below)
Marc Gravell
2008-10-08 14:44:15
Except that it does. You even said so about the ISerializable interface.
Chris Lively
2008-10-08 16:36:30
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
2008-10-09 16:47:08
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
2008-10-09 19:35:33
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
2008-10-08 14:03:31
+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
2008-10-08 14:46:07
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
2008-10-09 12:25:35
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
2008-10-09 16:43:20
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
2008-10-09 16:45:09