Note that there are some explanatory texts on larger screens.

plurals
  1. POObject reference not set to an instance of an object when variable is declared in class level
    primarykey
    data
    text
    <p>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.</p> <p>For example, this is my latest project to create a program to display the state of substances in a specific temperature:</p> <pre><code> 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 &lt;= WATER_FP Then strSolid &amp;= "Water " ElseIf sngTemperature &gt;= WATER_BP Then strGas &amp;= "Water " End If If sngTemperature &lt;= ETHANOL_FP Then strSolid &amp;= "Ethanol " ElseIf sngTemperature &gt;= ETHANOL_BP Then strGas &amp;= "Ethanol " End If If sngTemperature &lt;= MERCURY_FP Then strSolid &amp;= "Mercury " ElseIf sngTemperature &gt;= MERCURY_BP Then strGas &amp;= "Mercury " End If If sngTemperature &lt;= OXYGEN_FP Then strSolid &amp;= "Oxygen " ElseIf sngTemperature &gt;= OXYGEN_BP Then strGas &amp;= "Oxygen " End If If strSolid &lt;&gt; vbNullString Then strSolid = "Substances that are in solid state are " &amp; strSolid Else strSolid = "No substances are in solid state." End If If strGas &lt;&gt; vbNullString Then strGas = "Substances that are in gaseous state are " &amp; strGas Else strGas = "No substances are in gaseous state." End If lblMessage.Text = strSolid &amp; ControlChars.CrLf &amp; strGas End Sub End Class </code></pre> <p>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 <code>btnDisplayState_Click</code>, the program works perfectly. Now I know what caused the error, but furthermore I wanted to know why this problem occurs.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload