Sealing a Method

An entry about c# 3.0 Publication date 21. September 2007 17:08

I'm sure you've often come across usages of the seal keyword to used to stop people from inheriting from and changing the behavior of a given class. The .NET Framework includes several sealed classes they dont want us to extend - SqlConnection for example. But the seal keyword can also be used to seal a method (or a property for that matter), allowing us to seal only parts of the behavior of a class, while still allowing inheritance. Lets look at a silly example:

public abstract class BaseAction
{
public abstract void Execute();
}
public abstract class ConditionalAction : BaseAction
{
public sealed override void Execute()
{
if (Decide())
{
ExecuteTrueAction();
}
else
        {
ExecuteFalseAction();
}
}
protected abstract bool Decide();
protected abstract void ExecuteTrueAction();
protected abstract void ExecuteFalseAction();
}

By sealing Execute() in ConditionalAction, we disallow overriding this method in classes that extend it. Instead, such classes must now implement Decide, ExecuteTrueAction and ExecuteFalseAction. Obviously, a class can still hide the implementation of Execute by using the new keyword, but that will not affect the behavior of any code that references instances of it as a ConditionalAction - remember that hiding is not the same as overriding.

Be the first to rate this post

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.

NDC 2010

The conference to attend this summer happens June 16th-18th in Oslo, Norway. Are you going? Be sure to catch my talk on AOP while you're there!

 

Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS