-1

I'm writing a blackjack program but my problem is what's the solution when creating an object that has a list of other objects, but when I create the object at first, the list is empty. I think that's why I'm getting this error. Below is my code where I initialize a player as having an instance of a hand in the player's constructor but I get the "object reference not set to an instance of an object" error message when I call the method playerHand.Hit(card);

public class Player
{
    private string name;
    public Hand playerHand;

    public Player()
    { }

    public Player(string name)
    {
        this.Name = name;
        this.playerHand = new Hand();
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public void TakeCard(Card card) 
    { playerHand.Hit(card); }`

`

public class Hand
{
    public List<Card> hand;
    public Hand()
    {
        hand = new List<Card>();
    }
    public int handValue;`

    public void Hit(Card card)
    {
        hand.Add(card);
    }

    public int HandValue()
    {
        foreach (Card card in hand)
            handValue += (int)card.value;

        return handValue;
    }
}

public class Game
{
    public Game(IEnumerable<string> playerNames)
    {
        List<Player> players = new List<Player>();
        foreach (string name in playerNames)
            players.Add(new Player(name));
        Player dealer = new Dealer();
        players.Add(dealer);
        Deck playingDeck = new Deck();
        Deal(playingDeck, players);
        Play(playingDeck, players);
        DisplayResults(players);
    }       

    public void Deal(Deck deck, List<Player> players)
    {
        deck.Shuffle();
        for (int i = 1; i < 3; i++)
            foreach (Player player in players)
                player.TakeCard(deck.Deal());                
    }

1 Answers1

4

You have this line:

Player dealer = new Dealer();

You didn't show us the code for Dealer. But, it's obvious from the code that Dealer : Player. Note that your default constructor for Player never initializes Player.playerHand. If the default constructor for Dealer calls the default constructor for Player (and it does by default), then playerHand will be null for dealer.

So, my guess is that playerHand.Hit(card); is giving you a NullReferenceException when invoked for the dealer because you never intialized Player.playerHand.

To fix it, just provide an initializer

public Hand playerHand = new Hand();

and remove the corresponding line from the constructor Player(string).

Finally, and this is an aside, you have way too many public variables in your classes. You're "leaking" variables that consumers of your class can modify without restraint and muck up your invariants. Encapsulation is the name of the game.

jason
  • 236,483
  • 35
  • 423
  • 525