Avoiding debugger warning in IsNothing() statement

I am using Visual Studio 2012 and have the following code block. The code checks the file type of a specific file (that's why there are return True/False in it). If it encounters an error it also returns false. The warnings I get are that I use the fs/br variables before they are initialized, which is true. That's why I have the IsNothing statements, but I get the warning IN the IsNothing statements and I have no idea how to avoid that because I don't want to put the fs = New FileStream(fn, FileMode.Open) and br = ... statements outside the Try/Catch block.

The code itself works so the warning is not really a problem, but it still bothers me to have them. Does anyone see a solution how this block can be changed to offer the same safety without warnings?

Both VB.NET or C# answers are welcome.

            Dim fs As FileStream
            Dim br As BinaryReader
            Try
                fs = New FileStream(fn, FileMode.Open) 'Open the file
                br = New BinaryReader(fs) 'Initilize the reader
                'File reading code omitted here
                br.Close() 'Close the reader and underlying stream
            Catch
                If Not IsNothing(fs) Then fs.Close() 'Warning here
                If Not IsNothing(br) Then br.Close() 'and here
                Return False
            End Try
Jon Skeet
people
quotationmark

That's why I have the IsNothing statements

That suggests you expect the values to be IsNothing before they're given a specific value. In C#, this wouldn't just be a warning - it would be an error.

I have two suggestions:

  • If you really want to follow this pattern, just set the values to Nothing to start with:

    Dim fs As FileStream = Nothing
    Dim br As BinaryReader = Nothing
    
  • If at all possible, reorganize your code so you can just use Using statements instead, which will close the streams at the end of the block either way. We can't tell enough about the rest of the code to help you do that at the moment though.

people

See more on this question at Stackoverflow