Solving Multiple Inheritance in C# 3.0

In .Net on September 17, 2008 by Matt Grande Tagged: , , ,

I recently came across a problem while trying to DRY my old code.  I had been two classes, one that inherits from DropDownList called DynamicDropDownList, and one that inherits from CheckBoxList called DynamicCheckBoxList.

Since both DropDownList and CheckBoxList inherit from ListControl, there was some duplicated code.  However, I was at a loss as to how to remove that since C# doesn’t support multiple inheritance.

I eventually came up with the following solution using Extensions Methods, which are new to C# 3.0.

First, create a new class to hold your duplicated methods.  Note that both the class and the method are declared static.

namespace YourNamespace
    public static class DynamicListControlExtension
        public static void DoYourStuff(this ListControl listControl)
            // Do your stuff here.

Then, in your soon-to-be-DRY classes include the following:

using YourNamespace;

namespace YourOtherNamespace
    public class DynamicDropDownList
        public void RefactoredMethod()
            // This method could also be written like this if you prefer:

And there you have it!  You’ll notice that I’ve included the this qualifier.  It is necessary in this case.

As always, leave a comment if you have any questions.  Happy coding!


2 Responses to “Solving Multiple Inheritance in C# 3.0”

  1. I didn’t realize that you could use the ‘this’ keyword in a function parameter, as in the static method. What does that actually do?

  2. Hi Marcel,

    The ‘this’ keyword at the class level does essentially the same thing as it does at the method level. It specifies that the class never needs to be invoked to call its methods.

    You’ll notice that the namespace that DynamicListControlExtension is defined in is included in the class for DynamicDropDownList. This allows you to use “this.DoYourStuff()” rather than “DynamicListControlExtension.DoYourStuff().”

    Hope this helps,
    – Matt.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: