-1

Hi I'm doing something in C# and I've ran into an index out of range error and I don't get why. I have a list with objects that hold a string. User gets to add a number of string values and thus filling the list with that same number of objects. When I later try to access the list elements using a for loop it gives me the index out of range error! This is a parody of my code that basically sums it up:

class game
{

    public List<Player> PlayerList = new List<Player>();
    public List<Player> Playerlist 
    {
    
        get { return PlayerList; }
    
    }

    public static int PlayerCount = 0;
    public void PlayGame()
    {

        Console.WriteLine("ENTER NUMBER OF PLAYERS: ");
        PlayerCount = int.Parse(Console.ReadLine());
        for (int n = 1; n < PlayerCount + 1; n++)
        {

            Console.WriteLine("ENTER NAME FOR PLAYER " + n + ":");
            PlayerList.Add(new Player() { PlayerName = Console.ReadLine() });

        }

        Player playeraccess = new Player();
        playeraccess.AddTurns();

    }
public class Player
{
    private static int throw1;
    public int Throw1
    {

        get { return throw1; }
        set { throw1 = value; }

    }
    private static int throw2;
    public int Throw2
    {

        get { return throw2; }
        set { throw2 = value; }

    }
    private static int throw3;
    public int Throw3
    {

        get { return throw3; }
        set { throw3 = value; }

    }
    int firstruncheck = 0;
    int turnloop = 0;
    int turncounter = 0;
    List<Turns> playerturn = new List<Turns>();
    public Player(string playername = "")
    {

        PlayerName = playername;

    }

    public string PlayerName { get; set; }

    public override string ToString()
    {
        return base.ToString();
    }
    public void AddTurns()
    {
        game gameaccess = new game();
        for(turnloop = 0; turnloop < game.PlayerCount; turnloop++) 
        {

            gameaccess.Playerlist[turnloop].playerturn.Add(new Turns());

On This last line I get an index out of range error. But it shouldn't happen since User has added elements into PlayerList, right?

  • 2
    this will answer your question: [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Ňɏssa Pøngjǣrdenlarp Mar 28 '21 at 17:33

1 Answers1

1

You are creating a new player list with every instance of game but keeping track of the count in a static variable (one instance of the count for all instances of the game).

To fix this you should decide whether you are keeping track of players per game (non-static list and count) or per run of your program (static list and count). For the latter, read up on static constructors.

AlanK
  • 1,827
  • 13
  • 16