0

I know I am doing something really dim here because it's a really simple bit of code, but I just cannot see it.

I have a class which has a single property of type Dictionary. This class simply looks up against a database table snd stores some values in the dictionary property. Trouble is, I am getting a System.NullReferenceException on the LookupValues.Add line in the code below:

Public Class Lookup
    Private _LookupValues As Dictionary(Of Integer, String)

    Public Sub New(LookupToRetrieve As String)
        Dim sqlQuery As String
        sqlQuery = "SELECT * From LookupValues (NOLOCK) WHERE lookup_name = @LookupName"

        Using connection As New SqlConnection(My.Settings.PDFProcessorConnectionString)
            connection.Open()
            Using comm As New SqlCommand(sqlQuery, connection)
                comm.Parameters.Add("@LookupName", SqlDbType.VarChar, 20).Value = LookupToRetrieve

                Dim rs As SqlDataReader = comm.ExecuteReader
                Dim dt As New DataTable
                dt.Load(rs)

                For Each row As DataRow In dt.Rows
                    LookupValues.Add(row.Item("lookup_value"), row.Item("lookup_text"))
                Next
            End Using
        End Using
    End Sub

    Public Property LookupValues As Dictionary(Of Integer, String)
        Get
            Return _LookupValues
        End Get
        Private Set(value As Dictionary(Of Integer, String))
            _LookupValues = value
        End Set
    End Property
End Class

I just cannot see what is wrong here - the query returns valid data, but it will not add it to the dictionary... What am I doing wrong?

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
Si Stone
  • 121
  • 2
  • 12
  • 1
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Visual Vincent Sep 28 '18 at 10:40
  • _LookupValues = New Dictionary(Of Integer, String) is missing. – IvanH Sep 28 '18 at 19:59

1 Answers1

1

You never create a Dictionary. Therefore _LookupValues will always be Nothing.

I would make LookupValues readonly. This means that you cannot assign it another dictionary. It does not mean that the dictionary itself is readonly.

Public ReadOnly Property LookupValues As New Dictionary(Of Integer, String)

You can use Visual Basic 14's ReadOnly Auto-Implemented Properties. I.e. you don't need to declare a backing field explicitly.

This still works:

LookupValues.Add(CInt(row.Item("lookup_value")), CStr(row.Item("lookup_text")))

I also recommend using Option Strict On.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • See, I knew I was doing something stupid! All it needed was a 'New' in the dictionary declaration. Thanks for the help :) – Si Stone Sep 28 '18 at 10:41