views:

113

answers:

3
A: 

Because interfaces support inheritance, you should just be able to say:

interface IElement : ISerializable 
{
  // IElement specific items
}

That will ensure any class that implements IElement also implements ISerializable.

neontapir
ISerializable is an option. But if I got the documentation right, I'd have to write the code for serialization. I was hoping there was an easier way. For example Attributes (which obviously is not working - at least not in a for me obvious way).
StampedeXV
+1  A: 

An abstract base class with the [Serializable] attribute is a very good choice, provided it suits your needs. All classes that inherit from the base class will also be marked as serializable.

Keep in mind that the Serializable attribute just says "this class can be serialized" whereas implementing ISerializable (or IXmlSerializable) means "this class wants manual control over its serialization". ISerializable isn't required for simple serialization.

Update: you could also consider writing a custom FxCop rule to generate warnings if a class implements your interface without being marked serializable.

If your abstract class replaces the interface then it will cover all grounds, but if you keep your interface seperate then there is still the potential for a class to implement the interface rather than inherit from the base-class--so having a way to detect these classes is still good.

STW
A: 

First of all, you need to decide if you're using XML Serialization or runtime serialization. XML Serialization does not use [Serializable] or ISerializable.

XML Serialization will need to know the concrete types of all the classes you'll have implementing IElement. You do this with the [XmlInclude] attribute.

John Saunders
That one would also be a good idea, but it does not force the derived/implementing classes to do anything towards serialization.
StampedeXV
There's no way to force them to do anything.
John Saunders