Posted by: Cirilo Meggiolaro | 01/25/2009

Tip of the day #103 – Sealed classes and methods

Sealed classes

A sealed class is a class that cannot be inherited. The main purpose of a sealed class is to keep control over the code implementation where the developer may restrict an extended version of a class to be created to especially avoid misuse of functionality.

To achieve that you must declare your class with the sealed keyword (C#) or NotInheritable (VB):

public sealed class SealedClass
{
    public void M() { Console.WriteLine(“SealedClass.M()”); }
}

public class ClientClass
{
    private void ClientMethod()
    {
        SealedClass mySealedClass = new SealedClass();
        mySealedClass.M();
    }
}

The code above compiles correctly while the following code does not compile:

public sealed class SealedClass
{
    public void M() { Console.WriteLine(“SealedClass.M()”); }
}

public class DerivedClass : SealedClass
{ }

So, before you decide if a class must be designed as sealed or not, check if the functionality of this class may be affected whether a derived class is not developed properly and if it is worth. Avoid risks!

Sealed methods

While sealed classes cannot be inherited, sealed methods and properties cannot be overridden when declared as sealed. The following code shows this scenario:

public abstract class A
{
    public virtual void M() { Console.WriteLine(“A.M()”); }
    public virtual string P { get; set; }
}

public class B : A
{
    public sealed override void M() { Console.WriteLine(“B.M()”); }
}

A class can extend from the class B but the method M() cannot be overriden. The following code raises a compile error:

public class C : B
{
    public override void M() { }
}

Important: You cannot declare a method or property as sealed if it is not an override version of it. On our example, you could not declare a sealed method or property on class A.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: