1

Let's assume I have this very useful interface:

public interface IFoo
{
    void Bar();
}

I known that this interface will be used in a context that requires serialization/deserialization, so I made this interface to extend ISerializable to force all implementations of this interface to be serializable and to show this to interface clients:

public interface IFoo : ISerializable
{
    void Bar();
}

But now I have a problem. All concrete implementations of IFoo are forced to implement GetObjectData data, even in cases when it's perfectly fine to just mark a class with Serializable attribute:

[Serializable]
public sealed class FooWithString : IFoo
{
    public string MyString { get; set; }

    public void Bar()
    {
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue("MyString", MyString, typeof(string)); // This is pointless, but I have to do it
    }

    private FooWithString(SerializationInfo info, StreamingContext context)
    {
        MyString = info.GetString("MyString"); // And this is pointless too, but I have to do it
    }
}

This example is pretty painless, but image if I have a class with 5-6 integers? This hurts a lot!

Is there a way to achieve something like this:

[Serializable]
public sealed class FooWithString2 : IFoo
{
    public string MyString { get; set; }

    public void Bar()
    {
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        UseDefaultSerializationMechanism();
    }

    private FooWithString(SerializationInfo info, StreamingContext context)
    {
        UseDefaultDeserializationMechanism();
    }
}

Or even cooler:

[Serializable]
public sealed class FooWithString3 : IFoo
{
    public string MyString { get; set; }

    public void Bar()
    {
    }

    // No pointless implementations!
}
RX_DID_RX
  • 4,113
  • 4
  • 17
  • 27
  • 1
    See [What is the point of the ISerializable interface?](http://stackoverflow.com/questions/810974/what-is-the-point-of-the-iserializable-interface) - if you don't need explicit control of the serialization process you don't need to inherit the interface at all. – stuartd Dec 22 '15 at 12:11
  • @stuartd IFoo extends ISerializable, not concrete implementations. The whole point is to make sure that ALL implementations of IFoo are serializable and to show this to IFoo clients – RX_DID_RX Dec 22 '15 at 12:16
  • Well, if you're sure you need it and the `[Serializable]` attribute isn't enough, then yes you will need to provide the implementation. – stuartd Dec 22 '15 at 12:19

0 Answers0