GabourX
GabourX

Reputation: 283

AccessViolationException while adding item to a list

I am developing a Windows Phone 8.0 App in VS2010

and in some point , i decided to make 2 classes (Player,Game)

Game.cs

public class Game
{
    public string Name { get; set; }
    public bool[] LevelsUnlocked { get; set; }
    public bool firstTimePlaying { get; set; }

    public Game(int numOfLevels)
    {
        this.firstTimePlaying = true;
        this.LevelsUnlocked = new bool[numOfLevels];
    }
}

Player.cs

 public class Player
    {   

    public int ID { get; set; }
    public string FirstName{ get;  set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public int Rank { get; set; }
    public int Points { get; set; }
    public string RankDescreption { get; set; }
    public Uri Avatar { get; set; }
  public List<Game> Games;

        public Player()
        {
            Game HourGlass = new Game(6);
            Game CommonNumbers = new Game(11);

            Games.Add(HourGlass);
            Games.Add(CommonNumbers);

        }
}

When i debug , the app crashes at the Line : Games.Add(HourGlass); because of AccessViolationException, i don't see what is the problem of adding the item to the list .

so what is it ?

Upvotes: 1

Views: 164

Answers (2)

Simon Whitehead
Simon Whitehead

Reputation: 65079

You must initialize a list before using it.

This:

public List<Game> Games;

..needs to be this:

public List<Game> Games = new List<Game>();

I am surprised you are getting an AccessViolationException.. I would have expected a NullReferenceException.

Upvotes: 2

Bill Gregg
Bill Gregg

Reputation: 7147

You haven't set your Games to a new list.

 public List<Game> Games = new List<Game>();

        public Player()
        {
            Game HourGlass = new Game(6);
            Game CommonNumbers = new Game(11);

            Games.Add(HourGlass);
            Games.Add(CommonNumbers);

        }

Upvotes: 1

Related Questions