-1
Public Class Form1

    Structure Crap
        Dim CrapA As Integer
        Dim CrapB As Single
        Dim CrapC() As Long
        Private Sub Initialize()
            ReDim CrapC(0 To 100)
        End Sub
    End Structure

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim Stuff(0 To 2) As Crap

        Stuff(0).CrapA = 16
        Stuff(1).CrapA = 32
        Stuff(2).CrapA = 64

        'This is the line where the NullReferenceException is thrown
        Stuff(0).CrapC.Initialize()

        For x = 0 To 100
            Stuff(0).CrapC(x) = x ^ 2
        Next x

        MsgBox(Stuff(0).CrapA)
        MsgBox(Stuff(1).CrapA)
        MsgBox(Stuff(2).CrapA)

        For x = 0 To 100
            MsgBox(Stuff(0).CrapC(x))
        Next x

    End Sub
End Class

So this is a pretty simple program with a baffling error. All I want is an array in my user defined type. I'm moving from VB6 to .net and everything I've read, including What is a NullReferenceException, and how do I fix it? which is a hearty read, doesn't help. Seems I'm stuck in 1999, lol. I understand that the array CrapC is null, it's making it not null that's the problem.

Community
  • 1
  • 1
XJonOneX
  • 305
  • 2
  • 11
  • From [NullReference Exception in Visual Basic](http://stackoverflow.com/a/26761773/1070452): **`Missing the New operator is the #1 cause of NullReference Exceptions`** ...six inches later `Arrays must also be instantiated:...` – Ňɏssa Pøngjǣrdenlarp Sep 04 '15 at 12:15

1 Answers1

0

The error happens here:

Stuff(0).CrapC.Initialize()

because the Crap() contains three instances of Crap but you never initialize the CrapC field which is a Long(). So you can call Initialize on Nothing(null). In most cases you don't need this method anyway: "This method is designed to help compilers support value-type arrays; most users do not need this method."

Instead use this array initializer to get a Long() with 100 longs:

Stuff(0).CrapC = New Long(99) {}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939