Search code examples
arraysvb.netnullreferenceexception

Can't figure out making an Array based off of a Class


What I'm trying to do is create an array from a Class that holds a list of information.

What I've tried so far is this - First, create the Class:

Public Class PowerArray
    Public Name As String
    Public Action As String
    Public Cost As Integer
    Public Pool1 As String
    Public Pool2 As String
    Public Range As String
    Public Duration As String
    Public Tags As ArrayList = New ArrayList
    Public Desc As String
End Class

Then, define a new object that uses PowerArray as type, contained in a Public Class so it can be called in any sub:

Public Class GVar
    Public Shared CharPowers(100) As PowerArray
    Public Shared PCount As Integer = 0
End Class

But when I try to write to that object, it keeps throwing a Null Reference Exception.

Example:

Trying to write an entry to CharPowers(GVar.Pcount) (where PCount is currently 0, and "txt.PowerName.Text" is any string):

GVar.CharPowers(GVar.PCount).Name = txtPowerName.Text

...throws the exception. This happens no matter which value I try to write to.

I haven't had any major hangups going this route when defining a new object inside a sub using that type (not as an array, but just a simple object), so I'm guessing it's the object being an array that's throwing a fit. I just can't figure out how or why. It clearly exists, it's defined on startup.


Solution

  • Your array in GVar is an array of elements typed as PowerArray with a value of Nothing. You must create an instance of PowerArray and assign it to an element is the array before you can set a field of a PowerArray object.

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim PA As New PowerArray
        GVar.CharPowers(GVar.PCount) = PA
        GVar.CharPowers(GVar.PCount).Name = TextBox1.Text
        MessageBox.Show(GVar.CharPowers(GVar.PCount).Name)
    End Sub
    

    Are you planning on incrementing PCount? You would not need to keep track of where you are in the array if you used List(Of PowerArray).

    EDIT

    Public Class PowerArray
        Public Property Name As String
        Public Property Action As String
        Public Property Cost As Integer
        Public Property Pool1 As String
        Public Property Pool2 As String
        Public Property Range As String
        Public Property Duration As String
        Public Property Tags As New List(Of Object)
        Public Property Desc As String
    End Class
    
    Public Class GVar
        Public Shared Property CharPowers As New List(Of PowerArray)
    End Class
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim PA As New PowerArray
        PA.Name = TextBox1.Text
        GVar.CharPowers.Add(PA)
        For Each item As PowerArray In GVar.CharPowers
            MessageBox.Show(item.Name)
        Next
    End Sub