0

I have an interface IStorageManager that allows me to store data, different implementations are for json-file-based storage, xml-file-based, etc

I have the interface IStorable and I want to force all classes implementing IStorable to have the [Serializable] header. So in the IStorageManager I can implement it like this :

public interface IStorageManager
{
    IStorable Load<IStorable>(string Path);
    void Save<IStorable>(IStorable objToSave, string path);
}
public class XMLStorageManager : IStorageManager
{
    public void Save<T>(T objToSave, string path)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
        using (TextWriter writer = new System.IO.StreamWriter(System.IO.Path.GetFullPath(path)))
        {
            serializer.Serialize(writer, typeof(T));
        }
    }
}

Is there a way to specify that in the interface ??

Hammad Sajid
  • 312
  • 1
  • 3
  • 14
javirs
  • 1,049
  • 26
  • 52
  • 2
    No, there isn't. You can check at runtime, but unless you write your own code analyzer or rule, there is no way to do that at compile time. – Lasse V. Karlsen Apr 30 '19 at 07:56
  • 1
    `XmlSerializer` doesn't require the `[Serializable]` attribute, and in fact makes no use of it. See e.g. [Why doesn't the XmlSerializer need the type to be marked `[Serializable]`?](https://stackoverflow.com/q/392431) or [Why is Serializable Attribute required for an object to be serialized](https://stackoverflow.com/a/2983430). – dbc May 01 '19 at 06:15

1 Answers1

0

The short answer is No you can't enforce an Attribute through an interface. In principle, interfaces are about contracts (behaviour) while serialisation is about state which is not normally reflected in interfaces.

The options you have are:

  • Instead of using an interface for "storable" objects use an abstract class (like StorableBase) that consumer code should inherit from. Main drawback of this is that it restricts the types of classes the consumer code can use with your library. Also note that not all serialization libraries check all the class hierarchy when looking for Serializable attribute and some might check only the concrete class. You can on top of that implement the ISerializable interface on that abstract class to have more control over the serialisation process. See here for details.

  • Roslyn introduced the concept of Code Analyzers. You can create a custom code analyzer that checks at compile time for your rule. See here for more details and an example.

Mohammad
  • 1,930
  • 1
  • 21
  • 31