-
Notifications
You must be signed in to change notification settings - Fork 1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Proposal: a way of defining a class that is only derivable within an assembly #1854
Comments
Are you aware of the private protected visibility modifier? Declaring a constructor with private protected visibility gives a class that can only be inherited within the same assembly. Make all the leaf classed sealed and you have your sealed hierarchy. Here's an example from a series on my blog: public abstract class ValidationResult
{
private protected ValidationResult()
{
}
} Unless, I've misunderstood the intent of your proposal? |
I raised this proposal after having had just applied |
You can use There's nothing that C# can do to implement a feature like this. Without CLR support it would be exceptionally easy to avoid this limitation by using a downlevel version of the compiler, or any other language. |
You can also have base class with private constructor and all subclasses nested. public abstract class Component
{
private Component() { }
public class Some : Component { }
public class Other : Component { }
} To organize it better, make base class partial and subclasses each in different file. Often the explicit scope Component.Some is better for discoverability than using suffixes or prefixes. Where it isn't, |
This proposal is a duplicate of #485, where it uses the One interesting feature of |
This would allow creating sealed hierarchies which is often useful for reusable libraries with a defined scope. In some cases it's beneficial to not give the library user a false impression that a class is meant to be inheritable because it had to be made inheritable.
I am not too bothered about exhaustive type pattern matching on top of this. But if it's possible and does not require putting all classes in the same file and/or removing (polymorphic) behaviour than that's OK too. This is not about case/data/record classes, this is about normal OOP classes.
Example based on suggested
public internal sealed
phrase (to avoid new keywords):PS: introducing namespace scope in addition to assembly scope could be quite interesting too. Though this would not be limited to just this case.
The text was updated successfully, but these errors were encountered: