Home
C# 2010 All-in-One For Dummies
Explore Book
Buy On Amazon
You may decide that you don’t want future generations of programmers to be able to extend a particular class. You can lock the class by using the keyword sealed. A sealed class cannot be used as the base class for any other class. Consider this code snippet: using System;

public class BankAccount { // Withdrawal -- You can withdraw any amount up to the // balance; return the amount withdrawn virtual public void Withdraw(decimal withdrawal) { Console.WriteLine("invokes BankAccount.Withdraw()"); } }

public sealed class SavingsAccount : BankAccount { override public void Withdraw(decimal withdrawal) { Console.WriteLine("invokes SavingsAccount.Withdraw()"); } }

public class SpecialSaleAccount : SavingsAccount // Oops! { override public void Withdraw(decimal withdrawal) { Console.WriteLine("invokes SpecialSaleAccount.Withdraw()"); } }

This snippet generates the following compiler error: 'SpecialSaleAccount' : cannot inherit from sealed class 'SavingsAccount'

You use the sealed keyword to protect your class from the prying methods of a subclass. For example, allowing a programmer to extend a class that implements system security enables someone to create a security back door.

Sealing a class prevents another program, possibly somewhere on the Internet, from using a modified version of your class. The remote program can use the class as is, or not, but it can’t inherit bits and pieces of your class while overriding the rest.

About This Article

This article is from the book: 

About the book author:

John Paul Mueller is a freelance author and technical editor. He has writing in his blood, having produced 100 books and more than 600 articles to date. The topics range from networking to home security and from database management to heads-down programming. John has provided technical services to both Data Based Advisor and Coast Compute magazines.

Bill Sempf is a seasoned programmer and .NET evangelist specializing in .NET applications.

Chuck Sphar is a programmer and former senior technical writer for the Visual C++ product group at Microsoft.