2

I have been stuck for the past hour trying to initialize "one" card in my deck of cards. Everything works create but as soon as I try to add a Card to my deck I get a "null reference exception" error. I created a card with a value of 1 and 12 (suit, value) and try to add "the card object" to my list of cards. The values show up when I message box the information but my list will not take the card.

      Public Class deck
          'create the fields
          Private newDeck As List(Of Card)

          'create properties
          Property newDeck_Property As List(Of Card)
            Get
                Return newDeck
            End Get
            Set(value As List(Of Card))
                newDeck = value
            End Set
         End Property


      Sub New()
            Dim cardvalueinfo As CardValue
            cardvalueinfo.cSuite = 1
            cardvalueinfo.cValue = 12
            Dim newCardinsert As New Card(cardvalueinfo)
            MessageBox.Show(newCardinsert.oneCard_Prop.cSuite)
            MessageBox.Show(newCardinsert.oneCard_Prop.cValue)
            newDeck_Property.Add(newCardinsert) <--------------- null error here
      End Sub

  End Class

I would really appreciate anyone pointing me in the right direction. I am a noob

Thanks

1
  • before you go much further consider initializing the deck List with all the cards and then shuffling them. see this answer and this sample). You'll almost certainly be unhappy with the results of picking a random card from the deck list. Commented Mar 3, 2014 at 2:25

1 Answer 1

2

You need to initialize newDeck_Property before adding item to it :

newDeck_Property = New List(Of Card)

or put initialization along with declaration of the backing field :

Private newDeck As New List(Of Card)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! They both worked. Why wouldnt i need to initialize both of them as new? Why do I only need to do one of them. It seems like to me when you put New you are create a new list, so why would I need to initialize both lists (if that makes sense)
the 1st snippet above, implicitly assign newly created List(Of Card) to the backing field (newDeck). The 2nd snippet, implicitly pass newly created List(Of Card) to getter of newDeck_Property whenever the property being accessed. Doing both at the same time will also work, but useless. Can't explain better, hope you get the idea :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.