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!
}