user547995
user547995

Reputation: 2085

Unknown NullPointerException

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!

Upvotes: 0

Views: 2078

Answers (5)

Maged Samaan
Maged Samaan

Reputation: 1752

replace:

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

with

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

constructors in c# has no return type

Upvotes: 6

Paolo Tedesco
Paolo Tedesco

Reputation: 57202

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

Upvotes: 0

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174319

I think your method Cardstack really should be a constructor:

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

Upvotes: 4

mnflz
mnflz

Reputation: 126

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() ?

Upvotes: 0

Petar Minchev
Petar Minchev

Reputation: 47373

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.

Upvotes: 2

Related Questions