0

Can't seem to find what's wrong here, I'm using this method :

public void AddPlayerToTeam(Player player, Team team)
{
    Team t = new Team();
    if(team.PlayersList.Count>=20)
        return;
    if (!(team.PlayersList.Contains(player)))
        team.PlayersList.Add(player); 
}

and later in this test:

[TestMethod]
public void CheckTeamOfPlayer9()
{
    Assert.AreEqual(wcm.GetPlayerById(9).PlayerTeam.CountryName, "Japan");
}

I get the following error: Object reference not set to an instance of an object. with the null reference exception. This is the method the test runs:

public Player GetPlayerById(int playerId)
{
    var result = from b in Players
                 where b.PersonId.Equals(playerId)
                 select b;

    return result.FirstOrDefault(); 
}

Any one has an idea?

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
user2023203
  • 546
  • 1
  • 12
  • 19
  • 3
    why do you create a new Team `t` in your first method? – Jonesopolis Nov 12 '13 at 18:25
  • 1
    Your debugger will tell you where the problem is. Some referenced object is null. – Bart Friederichs Nov 12 '13 at 18:25
  • 3
    Where are you creating a player with ID 9? `GetPlayerById` will return null if there's no such player... – Jon Skeet Nov 12 '13 at 18:25
  • `wcm.GetPlayerById(9).PlayerTeam` is the culprit. Either wcm, GetPlayerById(9) or PlayerTeam is returning null. – crthompson Nov 12 '13 at 18:26
  • 1
    And what would you like us to do? Do you want us to guess which of the references contains a null reference? It's impossible for us to see and very easy for you to check, since you are running your program and having presumably using a debugger. – Steven Nov 12 '13 at 18:30

1 Answers1

1

return result.FirstOrDefault() will return a default value if thaere is no match. In the case of Player, that is null.

Check the result of wcm.GetPlayerById(9). Presumably it is null.

David Arno
  • 42,717
  • 16
  • 86
  • 131