0

Hy!

I want to make a cardgame in c# The debugger always throws a NullPointerException. But the var card isn't null (it has a value shown during the debugging) The problem have to be in cards.add().

My Code:

namespace Uno_Logic
{
    class CardStack
    {
        private List<Card> cards;
        public void Cardstack()
        {
            cards = new List<Card>();
        }
        public void fillCardstack ()
        {
            for (Card_Value value = Card_Value.One; value <= Card_Value.DrawTwo; value++)
            {
                for (Card_Colour colour = Card_Colour.Yellow; colour < Card_Colour.Black; colour++)
                {
                    Card card = new Card(colour, value);
                    Card card2 = new Card(colour, value);
                    cards.Add(card); //**here throws the debugger the Exception**
                    cards.Add(card2);
                }

            }
         }
      }
   }

Please help!

user547995
  • 1,938
  • 8
  • 32
  • 57

5 Answers5

6

replace:

    public void CardStack()
    {
        cards = new List<Card>();
    }

with

    public CardStack()
    {
        cards = new List<Card>();
    }

constructors in c# has no return type

mBotros
  • 1,674
  • 1
  • 19
  • 39
4

I think your method Cardstack really should be a constructor:

public CardStack()
{
    cards = new List<Card>();
}
Daniel Hilgarth
  • 159,901
  • 39
  • 297
  • 411
2

Then your cards variable is null. You haven't initalized it, because you probably haven't called the Cardstack() method. By the way it is better the cards = new List<Card>(); to be in a constructor.

Petar Minchev
  • 44,805
  • 11
  • 98
  • 117
0

This is not the card variable which is null when the exception is throwing : this is the cards variable which is null. Are you sure to call Cardstack() before calling fillCardstack() ?

mnflz
  • 66
  • 1
  • 3
0

I think you wanted to declare a constructor for your CardStack class and initialize cards there.
If it's so, just remove 'void' before the CardStack method declaration, so it will become a constructor:

    public Cardstack() {
        cards = new List<Card>();
    }
Paolo Tedesco
  • 49,782
  • 29
  • 130
  • 181