Is it possible in C# to force a sealed class through an interface or wildcard? For example something like:
public interface A<SealedItem> where SealedItem : sealed
or maybe something like:
public sealed interface A {}
public class B : A // B is now sealed.
This may sound weird but I would like to "force" a sealed instance for conventions shake. Does something like this exists?
Extra context: I have request objects that are exposed through an API. I only use the request object for "reading" the data. These request objects may change over time, however, I don't want these request objects to influence each other. Using inheritance in my request objects can cause "problems". So "forcing" a sealed class would be nice in my case I guess.
Why Inheritance can be bad in my situation: Let's say I have the following requests:
public class RequestA { public int Number { get; set; } }
public class RequestB : RequestA { public int Id { get; set; } }
Both requests use the value number in this example. Let's say the implementation of RequestA changes and it doesn't need the number
value anymore. My code for request B will now break (just a small example). Another example is when RequestA gets a new property that is not used by Request B. I now have an unused property in the logic for my RequestB.
No, it is not possible.
The fact that the class is
sealed
simply means it can't be inherited.You can only use generic constraints for things that controls how a type can be used - if it's a class or a struct, if it implements an interface or is derived from a specific type or if it has a public constructor that takes no parameters.
An interface can't be marked as
sealed
.The one thing that you can do to prevent inheritance is to use value types - structs can't inherit from anything other than the
ValueType
special class (and that's beyond your control), nor can the be inherited from -from Structs (C# Programming Guide):
however this will probably not be a good choice in most cases, especially if you need reference type semantics in your code (and in most cases, you do).
Update - followed by an update to the question:
You can create all your request classes as sealed - and leave comments in the code for future developments that requests should be sealed and explain why - but that's probably all you can do, other than using structs instead of classes (which might not be a bad idea, if it's only for API requests.)
Check out Choosing Between Class and Struct to see if your requests meets the guidelines: