Sometimes get this error "Object reference not set to an instance of an object" when I declare a variable in class level, and use that variable in a procedure.
For example, this is my latest project to create a program to display the state of substances in a specific temperature:
Public Class Form1
Const WATER_FP As Integer = 0
Const WATER_BP As Integer = 100
Const ETHANOL_FP As Integer = -114
Const ETHANOL_BP As Integer = 78
Const MERCURY_FP As Integer = -39
Const MERCURY_BP As Integer = 357
Const OXYGEN_FP As Integer = -219
Const OXYGEN_BP As Integer = -183
Dim strSolid As String = vbNullString
Dim strGas As String = vbNullString
Dim sngTemperature As Single = CSng(txtTemperature.Text)
Private Sub btnDisplayState_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayState.Click
If sngTemperature <= WATER_FP Then
strSolid &= "Water "
ElseIf sngTemperature >= WATER_BP Then
strGas &= "Water "
End If
If sngTemperature <= ETHANOL_FP Then
strSolid &= "Ethanol "
ElseIf sngTemperature >= ETHANOL_BP Then
strGas &= "Ethanol "
End If
If sngTemperature <= MERCURY_FP Then
strSolid &= "Mercury "
ElseIf sngTemperature >= MERCURY_BP Then
strGas &= "Mercury "
End If
If sngTemperature <= OXYGEN_FP Then
strSolid &= "Oxygen "
ElseIf sngTemperature >= OXYGEN_BP Then
strGas &= "Oxygen "
End If
If strSolid <> vbNullString Then
strSolid = "Substances that are in solid state are " & strSolid
Else
strSolid = "No substances are in solid state."
End If
If strGas <> vbNullString Then
strGas = "Substances that are in gaseous state are " & strGas
Else
strGas = "No substances are in gaseous state."
End If
lblMessage.Text = strSolid & ControlChars.CrLf & strGas
End Sub
End Class
Upon debugging, I get an error as described above, without any highlight of where the code is causing the problem. However, if I move the variables into btnDisplayState_Click, the program works perfectly. Now I know what caused the error, but furthermore I wanted to know why this problem occurs.