Null Reference Exception in VB.Net

Rich Goldberg 161 Reputation points
2022-06-08T04:32:07.387+00:00

Still new to OOP, and can’t figure out what I’m missing….

In VB.Net, in class Class1, I have defined class FormFld:

Public Class FormFld
    Public Property ScrField As Control ' A control on the form
    Public Property DbField As String   ' Its corresponding field name in the database
End Class

Also in Class1, I define an object, Indiv, which contains FormFlds, which will hold a list of FormFld objects:

Public Class Indiv
    Public FormFlds As List(Of FormFld) ' List

    Public Sub New()
    End Sub
End Class

It seems to me that my constructor doesn’t need to do much.

Later on, one of my Windows forms attempts to create an Indiv object and store its form information in FormFlds:

Dim ff As New Indiv()
ff.FormFlds.Add(New FormFld With {.ScrField = TxtFullName, .DbField = "LastName" })

Setting a breakpoint and stepping through the code, I see that the Dim is successful, and I get a new Indiv object. However, when executing the ff.FormFlds.Add, I receive

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Can anyone tell me what I’m doing wrong?

Developer technologies | VB
0 comments No comments
{count} votes

Accepted answer
  1. Olaf Helper 47,441 Reputation points
    2022-06-08T05:55:41+00:00

    Public FormFlds As List(Of FormFld) ' List

    You defined the variable FormFlds, but you newer defined it using the new operator, so the variable is of state NULL => Exception when the code acesses it.
    See
    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/new-operator

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Jiachen Li-MSFT 34,221 Reputation points Microsoft External Staff
    2022-06-08T08:15:07.777+00:00

    Hi @Rich Goldberg ,
    Change

         Public FormFlds As List(Of FormFld) ' List]      
    

    To

         Public FormFlds As New List(Of FormFld) ' List  
    

    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.