VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,768 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi
When i run my project in 2017, it works just fine but when i run it in 2019, i get a System.NullReferenceException. Here is my function
Public Function GetConnection() As SqlConnection
Dim Connection As SqlConnection = Nothing
Dim bNeedAdd As Boolean = False
Try
Connection = CType(_Connections(ConnString), SqlConnection)
Catch ex As Exception
End Try
If Connection Is Nothing Then
bNeedAdd = True
End If
If Connection Is Nothing OrElse Connection.State = ConnectionState.Broken OrElse Connection.State = ConnectionState.Closed Then
Try
Connection.Dispose() <--- Error line in 2019
Connection = Nothing
Catch ex As Exception
Debug.Print("Connection already exists")
End Try
Connection = New SqlConnection
End If
'Always return an open connection
If Connection.State = ConnectionState.Closed Then
Connection.ConnectionString = ConnString
' Connection.Open()
End If
If bNeedAdd Then
_Connections.Add(ConnString, Connection)
End If
Return Connection
End Function
Seeing as this line is inside a Try Catch, I am wondering why its throwing this error. Is there a setting or a reason why this behaviour occurs?
Thanks
Hi,
if Connection Is Nothing you get NullReferenceException:
Dim Connection As SqlConnection = Nothing
Dim bNeedAdd As Boolean = False
Try
Connection = CType(_Connections(ConnString), SqlConnection)
Catch ex As Exception
End Try
If Connection Is Nothing Then
bNeedAdd = True
End If
If `Connection Is Nothing` OrElse ... Then
Try
Connection.Dispose() <--- Error line in 2019
Change your code:
If `Connection Is Nothing` OrElse ... Then
Try
Connection?.Dispose()
Thanks for the reply. The question mark (null Conditional Operator) makes all the difference :)