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?
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With