views:

128

answers:

2

I normally use C# and I'm attempting to convert a qbasic programmer to the joys of object oriented programming by easing him into VB 2005.

Below is a extremely simplified version of what I'm trying to accomplish. It successfully compiles, but all members in the array of card objects are set to "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
+2  A: 

Yes, when you create an array in .NET, every element of the array is set to the default value of the element type - which is null/Nothing for classes.

You need to populate the array before you use it (or expect it to be full of null references).

Note that this would have behaved exactly the same way in C#.

EDIT: As no-one's actually posted population code that would work yet, 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
Jon Skeet
My hope was that the empty constructor for Card would be used, but apparently it's being ignored.
scottwed
Yes, it would be ignored. As I say, it's the same for both VB and C# - creating an array never populates it, you always end up with the default values.
Jon Skeet
Now that I've stared at it long enough that makes sense. You never could initialize field members during declaration directly or in this case indirectly. Thanks for the help
scottwed
It's too late for v4, but I'd like to see the option to automatically call the constructor for each element in an array built into .Net 5: perhaps using syntax like: Public cards(51) As New Card
Joel Coehoorn
A: 

You need to do some sort of

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

Apologies if the syntax of the for-each is off, I'm a C# guy normally. But the basic issue is that you haven't initialized each element of the array.

GWLlosa