An Beginner Immigrant from C sharp to Vb simple issue
Public Function ExecCommand(ByVal sql 开发者_StackOverflow社区As String) As SqlDataReader
Dim dReader As SqlDataReader
Dim cmd As New SqlCommand()
cmd.CommandText = sql
cmd.Connection = sm
Dim isOpened = OpenConnection()
If isOpened Then
dReader = cmd.ExecuteReader()
CloseConnection()
End If
Return dReader
End Function
It says maybe a null refrence may occur at runtime for the declaring of that datareader. Why is that?
That's because the dReader
variable might not be initialized if the If condition is not satisfied. You could initialize it to Nothing
by default:
Dim dReader As SqlDataReader = Nothing
Obviously the caller of this method need to handle this case.
Also as a C# immigrant you are probably surprised why you are not getting a compile time error but only a warning.
if OpenConnection() fails, then isOpened is false. The following block will not get executed and dReader will not have been assigned.
Public Function ExecCommand(ByVal sql As String) As SqlDataReader
Dim dReader As SqlDataReader // Not assigned yet
Dim cmd As New SqlCommand()
cmd.CommandText = sql
cmd.Connection = sm
Dim isOpened = OpenConnection() // Fails to connect
If isOpened Then // Not executed
dReader = cmd.ExecuteReader()
CloseConnection()
End If
Return dReader // Return value unknown
As a sidenote, CloseConnection() is not executed either so you might have some problems later.
add else statemnt in which assign dreader as null.
Public Function ExecCommand(ByVal sql As String) As SqlDataReader
Dim dReader As SqlDataReader=Nothing
Dim cmd As New SqlCommand()
cmd.CommandText = sql
cmd.Connection = sm
Dim isOpened = OpenConnection()
If isOpened Then
dReader = cmd.ExecuteReader()
CloseConnection()
End If
Return dReader End Function
精彩评论