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());
}