Can you prevent your class from being inherited?
Yes, you can prevent your class from being inherited by using the 'sealed' keyword in C#. A 'sealed' class is one that cannot be used as a base class for another class. In other words, it prevents inheritance from the 'sealed' class.
Here's how you can define a 'sealed' class:
public sealed class SealedClass
{
// Class members
}
Once a class is declared as sealed, it cannot be used as a base class for any other class. Attempting to inherit from a sealed class will result in a compilation error.
// This will result in a compile-time error
public class DerivedClass : SealedClass
{
// Class members
}
Here's another example in which derived class forcefully inherits from the 'sealed' class and showing the compile time error:
Using the 'sealed' keyword can be beneficial when you want to ensure that your class's behavior and functionality remain intact and not extended or modified by derived classes. It's often used for classes that are designed to provide a specific functionality and should not be altered through inheritance.