views:

782

answers:

4

There is probably is simple fix for this but I currently have code similar to

dim dr as dbDataReader

try
      dr = connection.getDataReader(sql_str)
Catch ex as sqlClientException
     log.error(ex)
finally 

  if not IsNothing(dr) then
    dr.close
  end if
end try

However Visual Studio still warns me that the

if not IsNothing(dr) then
        dr.close
      end if

Can cause a NullReferenceException. What is the best way to mitigate this? I can't move the declaration into the try block.

A: 

Your code is correct. In the finally statement, as long as you check to make sure your objects are not null, it won't throw a null reference exception based on what happens in your code.

Joseph Daigle
A: 

I don't remember exactly, how VB.NET initialize variable, but in C# you must set "dr" some value/reference before you use them somewhere.

I think this should work:

dim dr as dbDataReader

try
      dr = connection.getDataReader(sql_str)
Catch ex as sqlClientException
     log.error(ex)
     dr = Nothing ' there is the change '
' finaly block is not necesary '
end try

if not IsNothing(dr) then
  dr.close
end if
TcKs
This solution does not work for me in VS2008 SP1.
Jason Stangroome
What exactly is 'does not work'? Compile error ( if so, send the message please )? Or it doeas not work in run-time ( thrown exception? if so, send the exception.ToString() please ).I haven't VB.NET compiler on my current computer :(
TcKs
The compile-time warning that the original poster's code produces remains after applying your suggestion.
Jason Stangroome
+7  A: 

Explicitly initialize the dr declaration to Nothing as such:

Dim dr As DbDataReader = Nothing

And the warning will disappear.

Jason Stangroome
+4  A: 

If GetDataReader throws, dr will not be assigned and will still have its initial value. VB.NET does initialise references to Nothing, but the compiler will not let you rely on that.

If using .NET 2.0, I would recommend a Using statement:

Using dr As DbDataReader = connection.GetDataReader(sql_str)
    Try
        ' Do something with dr '
    Catch ex As SqlClientException
        log.error(ex)
    End Try
End Using
Mike Dimmick