views:

1198

answers:

4

I have an interface that defines some methods I would like certain classes to implement.

public interface IMyInterface
{
    MethodA;
    MethodB;
}

Additionally I would like all classes implementing this interface to be serializable. If I change the interface definition to implement ISerializable as below...:

public interface IMyInterface : ISerializable
{
    MethodA;
    MethodB;
}

...all classes must now explicitly implement serialization as far as I am aware, since if you implement ISerializable you must implement the GetObjectData member (and the necessary constructor to deserialize).

How can I insist classes using my interface be serializable, but without forcing them to custom implement serialization?

Thanks, Will

A: 

You could write a custom FxCop rule and validate check-ins against it.

Cristian Libardo
+1  A: 

If you want to use the default serialization then you need to add the SerializableAttribute . One alternative would be to use an abstract class instead of an interface, then add the SerializableAttribute to the abstract class. If you're implementing your own custom serialization then you want to implement ISerializable, otherwise stick with SerializableAttribute .

Ricardo Villamil
A: 

Thanks for the replies. It would be nice to be able to force classes derived from an interface to implement serialization without this then forcing them to custom serialize but it doesn't seem to be possible.

WillH
+3  A: 

There does not seem to be a way to do this, but I wish there were.

Note two things though:

  • The Serializable attribute can not be inherited from a base class, even if the base class is marked as abstract.

  • You don't technically need the Serializable attribute, IF you are using an XmlSerializer because it does not make use of object graphs.

Thrash505