Search code examples
c#classvariablesprivate

Checking a private value in another class [C#]


I'm making a simple dart game in the console for an assignment where I am to practice using private lists and variables everywhere. The basic flow of the program for some context is as follows:

  1. User lands in a menu
  2. User chooses from 1-4. (1 = Add player, 2 = Add CPU, 3 = Start game, 4 = Quit)
  3. Game starts. Players manually add their 3 throws per turn, and CPU gets theirs randomly.
  4. When a player or CPU reaches 301 score, the loop ends and you now see every throw made by the winner.

UML diagram for class structure context: https://i.sstatic.net/X2ITv.png

Everything is pretty much complete. I've made the program to such an extent that both players and CPUs are getting random values (are treated as CPU players), it prints out everything correctly and follows the flow to the end.

My issue now is that I want to be able to reach the is_CPU variable which is private in the Player class from the Game class and use it in an IF check, directing whether or not the values are manually added or randomly generated.

Pseudo-code:

FOREACH (var player in player_list)
  IF (is_CPU == TRUE) 
    THEN Assign random values 
  ELSE
    THEN Manually enter values

I tried messing around with the get-set stuff, but I don't fully understand how to use them and how they work. I have looked around on here and still don't see how I should be using them in this case, if at all.

I can think of one way to work around this and that is by making a method just for this where it checks that value and returns true/false, but that seems like a 'lazy' or improper way to do this, and comes with several downsides. I feel like there should be a better way to do this, one that won't come back to bite me in the ass later. Hopefully there is, and I can learn it by asking here.

EDIT: The variables and lists HAVE to be private. It is part of the exercise where we learn how to handle these.


Solution

  • In order to access private members of a class instance, you either have to define properties on that class with a public getter, as follows:

    public class Player
    {
        private Boolean m_IsCPU;
    
        public Boolean IsCPU
        {
            get { return m_IsCPU; }
        }
    
        // ...
    }
    

    or to change these members in order to make them public, as follows:

    public class Player
    {
        public Boolean IsCPU;
    
        // ...
    }
    

    Whatever you choose (I suggest you to go for the first approach), in any part of your code in which you have to check the IsCPU property/member for each instance of the Player class, you can just do as follows:

    foreach (Player player in players)
    {
        if (player.IsCPU)
            // Do Something...
        else
            // Do Something Else...
    }
    

    Some interesting links: