How can I combine these two similar methods into one?
c#
Solution
You could factor out the logic into a helper method:
private void ListFixup(object entity, List<Item> addList, List<Item> removeList)
{
LabEntity selectedItem = entity as LabEntity;
// don't forget your error checking here
addList.Add(selectedItem);
removeList.Remove(selectedItem);
}
private void btnAdd_Click(object sender, EventArgs e)
{
ListFixup(bindingSource1.Current, selectedLabsData, availableLabsData);
}
private void btnRemove_Click(object sender, EventArgs e)
{
ListFixup(bindingSource2.Current, availableLabsData, selectedLabsData);
}
I'm not sure this helps readability, but it does reduce code duplication.
Problem
The methods below are just inverses of one another. I suspect that I can combine the logic into one method. I prefer to avoid Reflection. Is it possible to combine them and maintain readability? ``` private void btnAdd_Click(object sender, EventArgs e) { LabEntity selectedItem = bindingSource1.Current as LabEntity; selectedLabsData.Add(selectedItem); availableLabsData.Remove(selectedItem); } private void btnRemove_Click(object sender, EventArgs e) { LabEntity selectedItem = bindingSource2.Current as LabEntity;//new binding source availableLabsData.Add(selectedItem);//called Add instead of remove selectedLabsData.Remove(selectedItem);//called Remove instead of Add } ```