You can subclass from LeaseContract just fine, no?
Sorry for being obtuse, but how could you respecify it even in
old-fashioned non-generic world?
Here is a sample what I did, which seems to work fine (create
a simple form with a DataGridView named uxDataGrid and try it):
using System;
using System.Collections;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
namespace RegularInheritanceTest
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
LeaseContract contract = new LeaseContract();
contract.AddLine(new LeaseContractLine());
uxDataGrid.DataSource = contract.Lines;
// The grid displays both ContractLineTestProperty &
// LeaseContractLineTestProperty...
}
}
// Contract & ContractLine class:
public class Contract
{
protected ContractLineCollection _lines = new
ContractLineCollection();
public Contract() { }
public void AddLine(ContractLine line)
{
_lines.Add(line);
}
public ContractLineCollection Lines { get { return _lines; } }
}
public class ContractLine
{
public int ContractLineTestProperty { get { return 1; } }
public ContractLine() { }
}
// LeaseContract & LeaseContractLine class:
public class LeaseContract : Contract
{
public LeaseContract() { }
}
public class LeaseContractLine : ContractLine
{
public int LeaseContractLineTestProperty { get { return 2; } }
public LeaseContractLine() { }
}
// ContractLineCollection class:
public class ContractLineCollection : CollectionBase
{
public void Add(ContractLine item)
{
List.Add(item);
}
public void Remove(int index)
{
if ((index > (Count - 1)) || (index < 0))
throw (new Exception("Index out of range: " + index));
List.RemoveAt(index);
}
}
}
This is the point behind my original question:
"a) Now, a question you've got to answer: do you still need to be able
to add arbitrary ContractLine instances to a LeaseContract?"
The reason I asked this question was to figure out if you needed an
inheritance hierarchy with the lines - and show that you had a
covariance problem if you did. Has your answer changed?
No, but let me try to clarify: If I create a LeaseContract, I will only
add LeaseContractLines to it, and if I create some other (further
sub-classed) class, I will only add lines belonging to that level
of subclassing to it. I will not mix different type of ContractLines.
But I need to be able to subclass more than one level deep from the
generic base class.
LeaseContract isn't a generic class, though, right? It's only the base
class that's generic in this design - i.e. ContractBase<>, yes?
Yes, but LeaseContract as written in my previous sample does not work -
it only stores ContractLines. It needs to store LeaseContractLines.
In order for it to store LeaseContractLines I need to do this:
public class Contract : ContractBase<ContractLine>
but then I am back to only being able to subclass directly from
ContractBase<T>...
Thanks for your patience,
Lars