Preventing inheritance in C#.NET: which modifier should be applied to a class to disallow deriving from it?

Difficulty: Easy

Correct Answer: Declare the class as sealed.

Explanation:


Introduction / Context:
Sometimes an API designer wants to stop consumers from deriving from a class (for safety, simplicity, or design reasons). C# offers a built-in way to accomplish this.



Given Data / Assumptions:

  • We are dealing with class-level modifiers.
  • We want to disallow inheritance.


Concept / Approach:
Use the sealed modifier on a class declaration to prevent inheritance: public sealed class MyClass { } Any attempt to derive from MyClass will be a compile-time error.



Step-by-Step Solution:

Identify the C# keyword for non-inheritable classes → sealed.Eliminate unrelated keywords (override, etc.).


Verification / Alternative check:
Create a sealed class and try deriving: the compiler reports an error that it cannot derive from sealed type.



Why Other Options Are Wrong:
They are either non-existent modifiers in C# (shadows, suppress) or apply to members (override), not to prevent inheritance at class level.



Common Pitfalls:
Confusing method-level override/new with class-level inheritance control; mixing VB terms (Shadows) with C#.



Final Answer:
Declare the class as sealed.

More Questions from Inheritance

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion