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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With