Question

I have the following code (ready to paste into linqpad). Basically there is a base 'model' class with a 'treemembermodel' class deriving from it.

class MemberModel
{
    public List<Member> Team = new List<Member>();

    public void IncreaseAge()
    {
        // Would like this to modify the Treemember
        Team[0].Age++;
    }
}

class TreeMemberModel : MemberModel
{
    public new List<TreeMember> Team = new List<TreeMember>();

    public void UpdateName(string newName)
    {

    }
}

Same for a Member class with a 'TreeMember' deriving from it.

public class Member
{
    public string Name;
    public int Age;
}

public class TreeMember: Member
{
    public string ParentName;
}

The idea is that the base member model stores a list of normal members, while the 'tree' model (and member) classes ensure a 'tree' structure by maintaining integrity between parent and subordinate fields.

This all seemed a good idea (the below example is stylised) - I figured any 'common' methods applying to both object types (eg 'increaseage' below) would modify the treeMember in the TreeModel when called from that model. However, calling 'increaseage' in my main method instead tries to access the 'Team' collection from the base 'MemberModel' instead, which of course doesn't exist.

void Main()
{
    TreeMemberModel t = new TreeMemberModel();
    t.Team.Add(new TreeMember() { Name = "original", Age = 10 });

    // Call method within derived class
    t.UpdateName("changed");
    Console.WriteLine (t.Team[0].Name);

    // Call method which drops down to base class method, and would like it to modify the TreeMemberModel's Team collection, not MemberModel's.
    t.IncreaseAge();
    Console.WriteLine (t.Team[0].Age);
}

I figure this is a covariance issue, and have tried a few things around making classes generic and so forth. Can I configure this so it drops back to the base class's methods while manipulating the elements of the TreeModel collection?

Was it helpful?

Solution

You should try following:

class MemberModel<TMember> where TMember : Member
{
    public List<TMember> Team = new List<TMember>();

    public void IncreaseAge()
    {
        // Would like this to modify the Treemember
        Team[0].Age++;
    }
}

class TreeMemberModel : MemberModel<TreeMember>
{
    public void UpdateName(string newName)
    {

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top