Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a class you want to extend which is sealed in the .NET library?

Tags:

c#

.net

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

like image 861
GurdeepS Avatar asked Mar 18 '09 09:03

GurdeepS


2 Answers

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.

like image 124
Jonathan C Dickinson Avatar answered Oct 11 '22 13:10

Jonathan C Dickinson


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.

like image 22
Neil Barnwell Avatar answered Oct 11 '22 15:10

Neil Barnwell