Search code examples
c#attributescustom-attributescompile-time

Ensure mutually exclusive interfaces at compile-time?


I'd like to ensure that two interfaces are never found on the same class at compile-time, similar to how AttributeUsage checks custom Attributes at compile-time.

e.g.:

[InterfaceUsage(MutuallyExclusive = typeof(B))]
interface A {
    //...
}

interface B {
    //...
}

class C : A, B { //should throw an error on compile time
    //...
}

I can obviously do this at runtime with reflection, but I'm interested in a compile-time solution.

I'd imagine that one probably doesn't exist out of the box - but is there a way to create a custom attribute that is run at compile-time, much like AttributeUsage is?


Solution

  • A different approach could be to change them to Abstract classes.