2.9 Preventing Object Inheritance

 <  Day Day Up  >  

You don't want your class to be used as a base class for other classes.


Technique

Use the sealed keyword within the declaration of your class:

 
 public sealed class HDTV : Television { } 

Comments

When you seal a class, no other class can derive from it. The most common reason you might want to consider doing so is if you feel the class is as specialized as you can get within the hierarchy of derived classes that you created. For instance, if I expanded the MediaDevice derivation further and created an HDTV class that derives from Television , then HDTV would be a good candidate for a sealed class.

You might be thinking that sealing a class doesn't add much value because all it does is prevent derivation, which itself limits the expandability of a class. Sealing a class also carries with it the added benefit of performance optimization. The runtime can call any of the virtual functions of that object using nonvirtual function-call techniques. However, if you disassemble an assembly containing a sealed class, you will notice that even though you call methods contained within the sealed class, the intermediate language (IL) instruction to call a virtual function, callvirt , is still emitted . The instruction for a nonvirtual method is the call IL instruction. Even though it sounds like it, there is no contradiction here. When the IL is just-in-time (JIT) compiled, which happens when the assembly is first executed, the callvirt instruction is optimized to call the method using a nonvirtual call. The only performance hit, which itself is negligible, is a simple check to ensure the this pointer is not null.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net