11

I was reading somewhere about how to handle the issue of wanting to extend a sealed class in the .NET Framework library.

This is often a common and useful task to do, so it got me thinking, in this case, what solutions are there? I believe there was a "method" demonstrated to extend a sealed class in the article I read, but I cannot remember now (it wasn't extension methods).

Is there any other way? Thanks

1

7 Answers 7

9

There is 'fake' inheritance. That is, you implement the base class and any interfaces the other class implements:

// Given
sealed class SealedClass : BaseClass, IDoSomething { }

// Create
class MyNewClass : BaseClass, IDoSomething { }

You then have a private member, I usually call it _backing, thus:

class MyNewClass : BaseClass, IDoSomething
{
   SealedClass _backing = new SealedClass();
}

This obviously won't work for methods with signatures such as:

void NoRefactoringPlease(SealedClass parameter) { }

If the class you want to extend inherits from ContextBoundObject at some point, take a look at this article. The first half is COM, the second .Net. It explains how you can proxy methods.

Other than that, I can't think of anything.

7
  • Because of this wrapping-style inheritance, I don't really understand the point of "sealed" classes - they clearly don't prevent you from, in practice, extending a class. The inventors of sealed classes must have known this, so what's the point in them really? To 'encourage' people not to extend a class? To make it 'more of a pain' to extend a class? Why not just say in the documentation, "this class should not be inherited"?
    – Jez
    Jan 4, 2013 at 9:27
  • @Jez If you're going to "just say in the docs, this class should not be inherited" I prefer setting it as sealed and not rely on docs. But that's really not its usage. It's nothing trivial, tho, I recommend you do some research. As I'm reading and learning about sealed I'm still clueless on why to use it, but too many people think classes should be sealed by default and then have the keyword unsealed instead.
    – cregox
    May 14, 2013 at 21:19
  • 1
    @Cawas I don't really like the mentality of sealed, which seems to be not to trust the developer. What if the developer reasonably wants to extend a class? This keywords just makes it more of a pain in the ass. It's a bug, not a feature, and I haven't seen any convincing argument otherwise. Again, I don't mind "encouraging" someone not to extend a class, but ultimately, the developer should be able to force the issue and not be stopped (or forced to use wrapping, breaking proper OOP) by a keyword.
    – Jez
    May 15, 2013 at 10:26
  • @Jez after more reading and discussing and considering, I have to agree. I could see only few good reasons for sealed to exist, but none that justify its existence and the trouble it causes. And specially nothing that justify so many people advocating it. All that being said I still think there's no point in "just say in the docs" if you can enforce it in the code. And I'm still hoping someone will give a good practical example on why it even exists (unlike this). I think there is a good reason somewhere.
    – cregox
    May 15, 2013 at 11:01
  • @Jez here is my final world on sealed classes: don't ever seal a class unless you know you'll have support issues with your clients.
    – cregox
    Sep 4, 2013 at 20:01
6

Extension methods is one way, the alternative being the Adapter Pattern. Whereby you write a class that delegates some calls to the sealed one you want to extend, and adds others. It also means that you can adapt the interface completely into something that your app would find more appropriate.

6

this method may have already been mentioned above by it's formal name, but i don't know it's formal name, so here it is. This example "extends" the TextBox class (example in VB). I believe an advantage of this method is that you do not need to explicitly code or expose built-in members. Hope this is relevant:

VB Class Module "MyTextBox":

public Base as TextBox, CustomProperty as Integer

Private Sub Init(newTextBox as TextBox)
    Set Base = newTextBox
End Sub

public Property Get CustomProperty2() As String
    CustomProperty2 = "Something special"
End Property

To call the code, you might say:

Dim MyBox as New MyTextBox
MyBox.Init MyForm.TextBox3

from here you have access to all built-in members, plus your custom members.

Debug.Print MyBox.Base.Text
MyBox.CustomProperty = 44

For extra polish, you can make Base the default property of the class, and then you can leave out "Base" when you call properties of the Base class. You call Base members like this:

Debug.Print MyBox().Text
MyBox().Text = "Hello World"

VBA Demo

2

Maybe use the Decorator pattern?

Other than extension methods, this is the only sensible technique I can think of.

2

No, you can't extend a sealed class in any legitimate way.

TypeMock allows you to mock sealed classes, but I doubt that they'd encourage you to use the same technique for production code.

If a type has been sealed, that means the class designer has not designed it for inheritance. Using it for inheritance at that point may well cause you lots of pain, either now or when the implementation is changed at a later date.

Prefer composition to inheritance - it's a lot more robust, in my experience. See item 16 in "Effective Java (2nd edition)" for more on this.

9
  • Thanks for the warning of the dangers and direction (book recommendation).
    – GurdeepS
    Mar 18, 2009 at 9:50
  • 1
    Effective Java is an awesome book, even for C# developers. Not all of it is relevant to C#, but it's extremely well written.
    – Jon Skeet
    Mar 18, 2009 at 9:54
  • 1
    I would not recommend using TypeMock outside of your test environment. Mar 18, 2009 at 10:12
  • Composition: stackoverflow.com/questions/554145/… - But could you elaborate more unsealed classes can generate lots of pain or even just give a good example?
    – cregox
    May 14, 2013 at 22:35
  • @Cawas: I don't have time to find a great example now, although I've seen a few recently. stackoverflow.com/questions/16548762 gives an example of the kind of problem that inheritance can introduce though - how implementation details start having to be documented in order to avoid misbehaviour.
    – Jon Skeet
    May 14, 2013 at 22:37
2

The only way I know to "extend" a sealed class without extension methods is by wrapping it. For example:

class SuperString
{
    private String _innerString;

    public SuperString(String innerString)
    {
        _innerString = innerString;
    }

    public int ToInt() 
    {
        return int.Parse(_innerString);
    }
}

You'd need to expose all of the same methods/properties as the string class.

Some frameworks allow you to extend existing objects. In WPF, see Dependency Properties. For Windows Forms, see IExtenderProvider.

0

How about extension methods? You can "add" additional methods that way, without having to deal with the inheritance restriction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.