Covers topics on the Microsoft Certification Exam for the .NET Framework (Exam 70-536, Microsoft .NET Framework - Application Development Foundation)

Monday, March 24, 2008

How can you prevent your class from being inherited by another class in the .NET framework?

You can protect your class from being inherited by another class by using the "sealed" modifier on your class. If any class tries to inherit from your sealed class, they will get an error. Why would anyone want to seal a class? Classes are sealed when you would like to prevent static members from being changed. So if you have a class that define a value for BLACK, you can use sealed to prevent other classes from changing (intentionally or unintentionally) changing BLACK to some other value other than the color of black.

The code below will not compile and will have have the following error:
'SealedExample.SealedErrorClass': cannot derive from sealed type 'SealedExample.ExampleClass'

Sealed Class Example

namespace SealedExample
{
sealed class ExampleClass
{
public void MethodToInherit()
{
Console.WriteLine("This class is sealed so you can't inherit this method");
Console.WriteLine("Even though the method is public");
}
}

class SealedErrorClass : ExampleClass
{
//This does not work because ExampleClass is sealed
}

}

Additional Resources
Using Sealed Classes in .NET (C# Corner)
Sealed Keyword (Microsoft)

No comments:

Support This Site

LinkShare  Referral  Prg