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?