[RESOLVED] [2005] Variable 'myStreamReader' is used before it has been assigned a value
I am receiving the following warning:
Quote:
Warning 1 Variable 'myStreamReader' is used before it has been assigned a value. A null reference exception could result at runtime.
Here's my code:
Code:
Public Sub loadData()
'this reads the textfile and loads the checkbox
Dim currentFields() As String
' The StreamReader must be defined outside of the Try-Catch block
' in order to reference it in the Finally block.
Dim myStreamReader As StreamReader
Dim myInputString As String
Dim rowCount As Integer = 0
' Ensure that the creation of the new StreamReader is wrapped in a
' Try-Catch block, since an invalid filename could have been used.
Try
' Create a StreamReader using a Shared (static) File class.
myStreamReader = File.OpenText(filePath)
' Begin by reading a single line
myInputString = myStreamReader.ReadLine()
' Continue reading while there are still lines to be read
While Not myInputString Is Nothing
currentFields = Split(myInputString, ",")
If currentFields(1) = "0" Then
lstApts.Items.Add(currentFields(0))
Else
lstApts.Items.Add(currentFields(0), True)
End If
rowCount += 1
' Read the next line.
myInputString = myStreamReader.ReadLine()
End While
Catch exc As Exception
' Show the error to the user.
MsgBox("File could not be opened or read." + vbCrLf + _
"Please verify that the filename is correct, " + _
"and that you have read permissions for the desired " + _
"directory." + vbCrLf + vbCrLf + "Exception: " + exc.Message)
Finally
' Close the object if it has been created.
If Not myStreamReader Is Nothing Then
myStreamReader.Close()
End If
End Try
End Sub
Warning caused on If statement of Finally block.
Re: [2005] Variable 'myStreamReader' is used before it has been assigned a value
This is just a warning that mystreamreader MAY NOT be anything by the time it reaches the Finally block.
You have mystreamreader DIMed as a streamreader, but it doesnt mean anything until you assign it with the File.OpenText method. If that were to fail, then mystreamreader would still be uninitialized when it reaches the Finally block.
That's why there's a warning. It's okay.
Re: [2005] Variable 'myStreamReader' is used before it has been assigned a value
You can get rid of that warning message by changing this:
vb.net Code:
Dim myStreamReader As StreamReader
to this:
vb.net Code:
Dim myStreamReader As StreamReader = Nothing
The IDE gives you the warning because it doesn't know whether you intended that variable to be Nothing or you simply forgot to assign a value to it. By explicitly setting the variable to Nothing you are telling the compiler that it is Nothing because you intended it to be Nothing and that you will take responsibility for making sure that it is not Nothing if and when it is accessed.