Actually, thanks to this splendid comment by user @Evk, I realized that it is almost possible to constrain the implementation of an interface to be a struct
(or analogously, a class
).
The interface could be implemented as a generic interface, where the generic type parameter is constrained to be a struct
that implements the interface itself:
interface IBar<T> where T : struct, IBar<T> { }
Now I can declare a struct
that implements IBar
:
struct BarStruct : IBar<BarStruct> { } // Works fine.
But, I cannot declare a class
that implements IBar
in the same way, since the generic type parameter is restricted to be a struct
:
class BarClass : IBar<BarClass> { } // Will not compile!
However, it is not a waterproof approach: as user @Igor points out in the comment below, the following will still compile:
class BarClass : IBar<BarStruct> { }