❔ ✅ Stopping any additional subclassing of a class
I've got the following code:
Is there a way of stopping any other classes subclassing
MyBase
other than the two here? I need to be able to do these subclasses, but don't want anyone to be able to do any more.24 Replies
kind of? none of them are very good though
you can put all 3 types in a different assembly, with the constructors of
MyBase
all being internal, which means only types in that assembly can be subclasses
or you can have the two derived classes be nested inside the base class, with a private constructorYeah, access modifiers is the way to go here.
but you should ask yourself why you need this and make sure this is a hard requirement, as this will break the extensbility of the system
actually, if you mean "anyone else" as in users of like a library you're writing, then yeah, just making the constructors of MyBase internal will do it
idk how I read that differently
making the constructors internal sounds like it will do the job.
In this case, I need all user subclasses to come from MyType1 and MyType2. However, there are some functions that will accept any subclass of MyBase
And yes, I'm confident that this is a hard requirement
can you clarify what you mean by "anyone else" thou? Will this be a library, or do you mean other developers in the same codebase?
This is in a library that is used by other applications
right. then just make
MyBase
internal and you are good"anyone else" could well include future me
Perfect - thanks - appreciate it
You make them internal. You can still inherit from the same assembly, but then it's something you can control yourself
If I make
MyBase
internal, then I can't make MyType
public, which I need
Making the constructor internal certainly worked well thoughAlternatively you make the accessibility
File
, assuming you're in .NET 7, and put both classes in the same file 🙃Prefer composition over inheritance for better modularity and therefore better encapsulation and avoid further inheritance. Make your classes sealed, implementing a public interface for the consumers of your library.
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Does it prevent classes being derived?
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
It works, also prevents the classes to be instantiated directly from outside the assembly. 👌
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
mark the class with sealed keyword
that stops further derivation of the derived, not more derived classes of the base
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
I tried to close it a few times but the bot was down. I’ll try again now
There we go
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
Oops
Closing again now
Thanks
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.