Correct use of array as member of field in VB 2005
I usually use C # and I am trying to transform a qbasic programmer into the joys of object oriented programming by loosening it up in VB 2005.
Below is an extremely simplified version of what I am trying to accomplish. It compiles successfully, but all members in the array of card objects are Nothing. The test line throws a NullReferenceException. What am I doing wrong?
Sub Main()
Dim deck1 As New Deck
Console.WriteLine("Test: " & deck1.cards(2).face)
End Sub
Class Card
Public face As String
Sub New()
face = "Blank"
End Sub
End Class
Class Deck
Public cards(51) As Card
End Class
source to share
Yes, when you create an array in .NET, each element of the array has a default value for the element type, which is null / Nothing for the classes.
You need to populate the array before using it (or expect it to be filled with null references).
Note that this was supposed to behave exactly the same in C #.
EDIT: Since no one has posted demographic code that would work, here it is:
Class Deck
Public cards(51) As Card
Public Sub New()
For i As Integer = 0 To cards.Length-1
cards(i) = New Card()
Next
End Sub
End Class
source to share