-1

So I have a constructor and a method that returns a card. I'm getting an InvalidOperationException for some reason. Anyone can think of anything?

The cards list is not empty, I just removed the card generation algorithm from the constructor here to make it easier to read.

Here's the code:

public Deck()
{
    cards = new List<Card>();
    cardStack = new Stack<Card>();
    // cards list gets populated here
    foreach (Card card in cards)
    {
        cardStack.Push(card);
    }
}

public Card drawCard()
{
    return cardStack.Pop(); // This line is giving me an InvalidOperationException
}

Thanks!

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
Sadiq
  • 2,249
  • 2
  • 24
  • 32
  • 3
    -1. We can't figure out a problem from code that doesn't have it. Please post some code that *adds at least one card* and *reproduces* the problem. Until then, the cards list is empty, and that's the cause. – R. Martinho Fernandes Apr 16 '11 at 02:19
  • 1
    It is always good to check if the stack is empty before trying to pop. Always. – manojlds Apr 16 '11 at 02:26

4 Answers4

1

Chances are that cardStack is empty when you call Pop(). I suggest that you check the number of cards in the stack before you pop it and do something reasonable if the deck is empty.

JSBձոգչ
  • 40,684
  • 18
  • 101
  • 169
1

Maybe this is a stupid question ... but are you checking the stack is non-empty before you pop it? According to the MS docs that's the only reason this exception should be thrown ...

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
David
  • 2,226
  • 32
  • 39
0

You have no cards in there!

You create a new list of cards and that list starts empty. Then you grab them all (read: none) and push them into the stack. You get an empty stack.

And then you try popping, but you can't pop from an empty stack. The InvalidOperationException and the reason ("the Stack<T> is empty") are right there in documentation.

You need to initialize your list of cards by adding some cards. Or maybe just remove the list and initialize the stack directly.

And you also need to make sure you're not popping too much. If you pop all the cards out of the stack, when you pop next, the stack will be empty, and you'll run into the same problem.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
0

Looking at that code, no cards actually get pushed onto cardStack (cards is initially empty). You're getting the exception because C# is telling you that there's nothing to pop.

helloworld922
  • 10,801
  • 5
  • 48
  • 85