Question: In .NET/C#, how does one prevent a class from being inherited by another class? In other words can the inheritance of class be blocked? Also, what is the reason one might want to block the inheritance chain?
The sealed keyword/modified in .NET can be used to block derivation from a class. An attempt to inherit from a class marked as sealed will result in a compile time error. Also, a sealed class cannot be an abstract class, since abstract classes are meant to be inherited and cannot be instantiated as is. In C#, structs are implicitly sealed hence they cannot be inherited. You do not need to use the sealed keyword on structs.
Usage:
The code below will not compile.
As to why one might want to block inheritance there are 2 main reasons. One is that the programmer does not want a class to be inherited as it might be the last class in the inheritance chain. Second is for runtime performace gains. Making a class sealed tells the compiler that there are no virtual functions for the class that will be overridden and the compiler can optimize the method invocations by transforming virtual function invocations into non-virtual invocations. This saves the time for lookup in the vtable.
The sealed keyword/modified in .NET can be used to block derivation from a class. An attempt to inherit from a class marked as sealed will result in a compile time error. Also, a sealed class cannot be an abstract class, since abstract classes are meant to be inherited and cannot be instantiated as is. In C#, structs are implicitly sealed hence they cannot be inherited. You do not need to use the sealed keyword on structs.
Usage:
public sealed class MySealedClass { ... }
The code below will not compile.
public class MyDerivedClass : MySealedClass { ... }
As to why one might want to block inheritance there are 2 main reasons. One is that the programmer does not want a class to be inherited as it might be the last class in the inheritance chain. Second is for runtime performace gains. Making a class sealed tells the compiler that there are no virtual functions for the class that will be overridden and the compiler can optimize the method invocations by transforming virtual function invocations into non-virtual invocations. This saves the time for lookup in the vtable.
No comments:
Post a Comment