As I develop more and more for a living I have been trying to perfect my developing skills with personal projects in hope to expand my professional career, one of these is the concept of Polymorphism.
The last few projects I have worked on, I have this model where I have a TableLayoutPanel, that is a grid of custom UserControls. To try and start reducing redundency coding, I am trying to build base classes of both the Component and UserControl. One part of this is I have a function in the TableLayoutPanel that is used to add the custom UserControls to the table. The function looks as follows
/// <summary>
/// Adds a new Item to the table
/// </summary>
/// <param name="item">Item to Add</param>
protected virtual void Add (object item)
{
Items.Add(new SelectableComponentBase(((SelectableComponentBase) item).ID));
Items.Last().Width = (this.Width - 20); //use 20 in case a scrollbar appears
Items.Last().Anchor = (AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top);
Items.Last().Clicked += new EventHandler(this.SelectableComponentBase_Clicked);
Controls.Add(Items.Last());
Controls [Controls.Count - 1].Invalidate();
ScrollControlIntoView(Controls [Controls.Count - 1]); //scrolls down to the bottom (where the item is added).
if (ItemAdded != null) //lastly fire the event that the item has been added
{
ItemAdded(Items.Last(), new SelectableComponentBaseEventArgs(Items.Last().ID, Items.FindIndex(x => x.ID.Equals(Items.Last().ID))));
}
}
As I mentioned, this adds a customer UserControl to the table, as well as some other code related to sizing, events, ext. Now my current problem here is that first line you see Items.Add(new SelectableComponentBase(((SelectableComponentBase) item).ID));
.
Items is a property within the TableLayoutPanel, that looks as follows
/// <summary>
/// Get the collection of SelectableComponentBases
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
protected virtual List<SelectableComponentBase> Items
{
get;
private set;
}
Here's the thing. I want to be able to preserve that "Add" function to the point that if I make a new UserControl that inherits the "SelectableComponentBase", and a TableLayoutPanel that inherits the base one you see, BUT, the TableLayoutPanel can use the base Add function, without having to override it (because most of the times that should work fine as is).
So again, I am trying to find a way where without having to override the base "Add" function, I can add a custom UserControl that inherits the base UserControl, to a custom TableLayoutPanel that inherits the base one.
Hopefully this all makes sense, I am having trouble putting the idea into word which is why I am coming here for help because I am not sure what might be the proper approach to this, or if it's even possible