Enforce attribute addition for all classes that implement an interface

157 Views Asked by At

Let's say I have the simplest of interfaces for all components in my program.

public interface IComponent
{               
}

I know that every single component to be written for the project has to implement this interface, and I know that all of these components will be saved to disk using C#'s BinaryFormatter. That means that every component has to be decorated with the [Serializable] attribute. Is there a way to enforce the addition of this attribute now?

I say "now" because I can find various SO questions that tell me this isn't possible - but all of the questions I can find are from 2008. Has anything in the C# spec changed since then? Or do I have to use one of the workarounds described in the old answers?

1

There are 1 best solutions below

0
Maciej On

You could write unit tests that picks ups all implementation of IComponent from your library using reflection and checks if they have the Serializable attribute on them. I don't belive anything new was introduced in .NET since 2008 that could make that check compile time specific, sorry.