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

      

0


source to share


2 answers


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

      

+2


source


You need to do something like

For Each currentItem As String in Me.face
 currentItem = "Blank"
End

      



Apologies if the for-each syntax is off, I am usually C #. But the main problem is that you haven't initialized every element of the array.

0


source







All Articles