Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Base class is marked Serializable are all child classes marked too?

I have a whole list of entity classes which I need to make Serializable (due to storing session state in SQL, but that's another story).

I have added the attribute [Serializable] and all seems to be fine.

All of my entity classes extend from the same base class. If I mark the base class as Serializable, does this mean all children are marked as Serializable too?

Thanks

like image 1000
Russell Avatar asked Dec 02 '09 05:12

Russell


People also ask

Can serializable class inherited in C#?

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.

Do subclasses need to implement serializable?

Yes. Subclass need not be marked serializable explicitly.

Is serializable attribute inherited?

This class cannot be inherited.

How do you mark a class as serializable?

The easiest way to make a class serializable is to mark it with the SerializableAttribute as follows. The following code example shows how an instance of this class can be serialized to a file. MyObject obj = new MyObject(); obj. n1 = 1; obj.


2 Answers

No, attribute is not inherited.

When you extend the class, it's possible to add features that might not be serializable by nature therefore .NET framework cannot assume for you that everything what extends serializable base class is also serializable.

That's why you must explicitly state [Serializable] attribute on every class individually.

like image 105
lubos hasko Avatar answered Oct 03 '22 17:10

lubos hasko


Nope, each one will have to be marked as [Serializable] specifically.

Also if you intend to serialize an object to XML which is of a derived type as though it is the base type you'll also need a [XmlInclude] attribute.

EG:

[Serializable]
public class BaseClass : ParentClass
{
}

[Serializable]
[XmlInclude(typeof(BaseClass))]
public class ParentClass
{
}

(Binary serialization, like what is used for sessions, do not need this)

like image 30
fyjham Avatar answered Oct 03 '22 18:10

fyjham