Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a common subclass to remove duplicate code

I have two classes one is derived from CheckBoxList and the second one from DropDownList. The code inside them is exactly the same. The only difference is that I need first one at places where I need to show checkboxlist and second one to show dropdownlist. Below is my code:

using System;
using System.Collections.ObjectModel;
using System.Web.UI.WebControls;

    namespace Sample
    {
        public class MyCheckBoxList : CheckBoxList
        {
            public int A { get; set; }
            public int B { get; set; }
            protected override void OnLoad(EventArgs e)
            {
                //dummy task
                Collection<int> ints = new Collection<int>();
                //........
                this.DataSource = ints;
                this.DataBind();
            }
        }
    }

The second one

using System;
using System.Collections.ObjectModel;
using System.Web.UI.WebControls;

namespace Sample
{
    public class MyDropDownList : DropDownList
    {
        public int  A { get; set; }
        public int  B { get; set; }
        protected override void OnLoad(EventArgs e)
        {
            //dummy task
            Collection<int> ints = new Collection<int>();
            //........
            this.DataSource = ints;
            this.DataBind();
        }
    }
}

Now as you can see the internal code is exactly the same which I want to avoid. How can I make a common class for it so as to remove code duplicacy?

like image 275
Rocky Singh Avatar asked Sep 28 '11 21:09

Rocky Singh


1 Answers

You can create a third class

public class Entity
{
    public int  A { get; set; }
    public int  B { get; set; }
    Collection<int> GetCollection()
    {
        //dummy task
        Collection<int> ints = new Collection<int>();
        //........
        return ints;
    }
}

And then use it in other classes

public class MyDropDownList : DropDownList
{
    public MyDropDownList() { Entity = new Entity(); }

    public Entity {get;set;}
    protected override void OnLoad(EventArgs e)
    {
        this.DataSource = Entity.GetCollection();
        this.DataBind();
    }
}
like image 141
meziantou Avatar answered Oct 22 '22 05:10

meziantou