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

user3363744
  • 167
  • 1
  • 9
  • before you go much further consider initializing the deck List with all the cards and then shuffling them. see [this answer](http://stackoverflow.com/a/8108702/1070452) and [this sample](http://blog.codinghorror.com/shuffling/)). You'll almost certainly be unhappy with the results of picking a random card from the deck list. – Ňɏssa Pøngjǣrdenlarp Mar 03 '14 at 02:25

1 Answers1

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)
har07
  • 88,338
  • 12
  • 84
  • 137
  • 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) – user3363744 Mar 03 '14 at 02:34
  • 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 :) – har07 Mar 03 '14 at 02:59