Posts Tagged ‘Extensions’

Articles

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.DoYourStuff();
            // This method could also be written like this if you prefer:
            DynamicListControlExtension.DoYourStuff(this);
        }
    }
}

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!