Home > database >  Make one instance of a class hold a collection of instances of another class in C#
Make one instance of a class hold a collection of instances of another class in C#

Time:12-23

New to C# and OOP programming. I understand the inheritance part and such.

What I am stuck with (for a small school project) is as follows:

  • I have a Class called Team
  • I have a baseclass called TeamMember
  • I have 3 classes (more specific team roles) that inherit from TeamMember
  • there can only be a certain amount of teammembers per team (i.e. 10 teammembers per team)

Team doesn't inherit from any other class, but (in the real world) a team does have teammembers in it (otherwise there is no team ofcourse).

What would be the correct way to make the connection between Team and TeamMember (or the more specific roles) so that 1 instance of Team has 10 instances of TeamMember 'in it'?

Could this be realized through an array? and if so, in what Class do I initialize this array and how do I populate it with the correct objects?

(excuse me if my terminology isn't as good as it should be. Still learning there as well so correct me if I can improve it somewhere and I will edit it)

CodePudding user response:

A nice way of doing it would be to do something like this:

public class Team
{
    private List<TeamMember> _teamMembers;

    public Team()
    {
        this._teamMembers = new List<TeamMember>();
    }

    public void AddTeamMember(TeamMember newTeamMember)
    {
        if (newTeamMember == null) return;

        if (this._teamMembers.Count < 10)
            this._teamMembers.Add(newTeamMember);
    }
}

So, what do we have here?

Rather than playing with arrays of set length and then rely on exceptions, I introduced a simple way of controlling the team members.

That class property is private so you can't add anything to it directly.

Instead, I create a public method which exposes a way of adding members to said list and this is where we control how many team members we can add.

I like to instantiate list properties in the constructor, so when you use the class you don't need to check to see if that list exists or not, instead we initialize it to an empty list as soon as the Team instance is created and then it's one less thing to worry about.

We can then make more design decisions and maybe we want the method to return a boolean result, true if someone was added and false if we didn't because we already have 10.

Now, you say TeamMember is a base class for other classes. This means that you can pass all of those classes to your team.

Let's say you have something like this :

public class SomeMember : TeamMember
    {
    }

you can still add that to your list like this :

var team = new Team();

var someMember = new SomeMember();

team.AddTeamMember(someMember);

The code works because it is based on the base class and it's a common way of doing things. It would also work if you had an interface for example.

However, one thing to keep in mind is that if you do things like this then you won't get access to whatever extra things your other classes offer, unless you cast them back from the base class to the implementing one.

CodePudding user response:

I'm not quite new to OOP ,but I'm just not a very wise dev. this quite interesting , it about how you design 3 classes of TeamMember's children.

I recommend you encapsulate each type of TeamMembers in class of Team Try imagine in your team you will have many ppl ,after that it's about how to design hierarchy of ppl in the team . In my case I divide the member into 3 lists of TeamMember's children. which each class will have special property that is prop1,prop2,prop3 (That when you think about OOP you will have to think about what to reuse , what is the different fields/methods provide for each member of different class ).

e.g.

   //Rextester.Program.Main is the entry point for your code. Don't change it.
//Microsoft (R) Visual C# Compiler version 2.9.0.63208 (958f2354)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            //Your code goes here
            Console.WriteLine("Hello, world!");
            Team t =new Team();
            t.AddTeamMember(  new TeamMembers_Child1(){ name ="n1" ,prop1 ="I'm a staff"   } );
            t.AddTeamMember(  new TeamMembers_Child2(){ name ="n2" ,prop2 ="I'm a manager"   } );
            t.AddTeamMember(  new TeamMembers_Child3(){ name ="n3" ,prop3 ="I'm a janitor"  } ); 
            t.AddTeamMember(  new TeamMembers_Child2(){ name ="n4" ,prop2 ="I'm an imposter "   } );
        }
    }
      
    public class TeamMember{
        public string name {get;set;}   
    }
     public class TeamMembers_Child1 : TeamMember{ 
         public string prop1 {get;set;}
    }
     public class TeamMembers_Child2 : TeamMember{ 
         public string prop2 {get;set;}
    }
     public class TeamMembers_Child3 : TeamMember{ 
         public string prop3 {get;set;}
    }

    public class Team{
        private List<TeamMembers_Child1> _member_role1;
        private List<TeamMembers_Child2> _member_role2;
        private List<TeamMembers_Child3> _member_role3;
        public Team(){
            _member_role1 = new  List<TeamMembers_Child1>();
            _member_role2 = new  List<TeamMembers_Child2>();
            _member_role3 = new  List<TeamMembers_Child3>(); 
        }
        /* as Andrei Dragotoniu 's answer the logic of Adding member will be in this function like team only have 2 manager , etc.*/
        public void AddTeamMember(TeamMember newTeamMember)
        {
            if (newTeamMember == null) return;
            else   if (this._member_role1.Count   this._member_role2.Count   this._member_role3.Count  < 10){
               if( newTeamMember is  TeamMembers_Child1)
               { 
                this._member_role1.Add( ( TeamMembers_Child1 )newTeamMember);
                   
            Console.WriteLine("Add role1");
               }else  if( newTeamMember is  TeamMembers_Child2)
               { 
                this._member_role2.Add(( TeamMembers_Child2 )newTeamMember);
                   
            Console.WriteLine("Add role2");
               } else if( newTeamMember is  TeamMembers_Child3)
               { 
                this._member_role3.Add(( TeamMembers_Child3 )newTeamMember);
                   
            Console.WriteLine("Add role3");
               }
            
            }
    
          
        }
    
    
     
    
    }
}


result  
> Hello, world! 
> Add role1 
> Add role2 
> Add role3 
> Add role2
  • Related