Share via

Visual studio 2017 vs 2019 - SysatemNullReferenceException

NachitoMax 416 Reputation points
2021-09-15T15:09:06.683+00:00

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

Developer technologies | .NET | .NET Runtime
Developer technologies | VB
0 comments No comments

Answer accepted by question author

Peter Fleischer (former MVP) 19,351 Reputation points
2021-09-15T16:00:32.18+00:00

Hi,
if Connection Is Nothing you get NullReferenceException:

  1. Set Connection to Nothing
     Dim Connection As SqlConnection = Nothing
     Dim bNeedAdd As Boolean = False
     Try
         Connection = CType(_Connections(ConnString), SqlConnection)
     Catch ex As Exception
    
  2. Ignore Error if there isn't Connection in _Connections
     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()

Was this answer helpful?

0 comments No comments

1 additional answer

Sort by: Most helpful
  1. NachitoMax 416 Reputation points
    2021-09-15T16:13:18.75+00:00

    Thanks for the reply. The question mark (null Conditional Operator) makes all the difference :)

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.