tags:

views:

173

answers:

4

I've written an owner-drawn TabControl, but our project also uses TabWorkspace which derives from TabControl. At the moment, I've got

public class OurTabControl : TabControl
{
     // some code that overrides protected methods
}

public class OurTabWorkspace : TabWorkspace
{
    // the same code
}

I'd like to only have the shared code appear in one place, so we don't have to maintain two copies. Is this possible in C#, and if so, how?

+7  A: 

You could do it using an interface and writing an extension method.

class OurTabControl: IBehavior
class OurTabWorkspace: IBehavior

interface IBehavior
{    
}

static class BehaviorExtensions
{
   static [returntype] RepeatedBehavior(this IBehavior behavior)
   {
       //repeated code here
   } 
}
Joseph
You can add extension methods to interfaces in C#? I never knew that. Cool.
David Seiler
Thats fine if you can swall the drawbacks, you need to ensure that there is a using statement for the namespace containing the extension class in each code file where these methods are to be used. More significantly the extension methods cannot manipulate private or protected members. On top of that if the shared code needed to maintain some additional state where would it be put. Of course there are many situation where these limitations are acceptable but in other cases its not solution.
AnthonyWJones
@Anthony The points you bring up are definitely valid. I wasn't thinking of trying to override the protected member with an extension method. I was thinking of calling the extension method inside the overidden method.
Joseph
+1  A: 

Perhaps refactor the shared code into a single set of static methods?

Yoopergeek
Why static methods?
AnthonyWJones
Perhaps I'm not fully understanding OP's question, but my understanding is that he has a derived TabControl and derived TabWorkspace, ("OurTabControl" and "OurTabWorksapce".) I read the question as saying that the two derived classes share common (currently copy-pasted code.) One possible way to make that a single set of methods is to refactor them to work as static methods which can be shared by both derived classes.
Yoopergeek
A: 

How about using a partial class? Or, what about defining all the shared methods in one class and have both inherited classes instantiate it.

Raj
how would a partial class help? that's just breaking up the code over multiple files.
Erich Mirabal
+1  A: 

You could create an internal helper class that contains the common code and reference it as a private member in OurTabControl and OurTabWorkspace. Since TabWorkspace extends TabControl you should be able to take advantage of polymorphism and pass TabControl parameters to methods in the helper class. You would still need to override any common methods in both of your extended classes and call the helper class methods and/or base methods from there.

Jamie Ide