Junior — Middle
Explain the concept of using the 'sealed' keyword in programming and its purpose.
sobes.tech AI
Answer from AI
The keyword sealed in C# is used to restrict inheritance of classes or overriding of methods.
-
For classes:
sealedprevents other classes from inheriting from this class. This is useful when you want to prevent further extension of a class, for example, for security or optimization. -
For methods: in combination with
override,sealedprevents further overriding of the method in derived classes.
Example:
public class BaseClass {
public virtual void Method() { }
}
public sealed class SealedClass : BaseClass {
public sealed override void Method() { }
}
// Attempting to inherit from SealedClass will cause a compile-time error
// class DerivedClass : SealedClass { } // Error
// Attempting to override Method in a class inheriting from SealedClass is also impossible
Using sealed helps control the architecture of the application and prevents unwanted changes in class behavior.