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
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.