Reputation: 6375
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
Upvotes: 1
Views: 153
Reputation: 27322
You can re-write this without having to use a nested Using block -you can do it all in one line - I don't believe you can do this in C#:
Try
Using fs As New FileStream(fn, FileMode.Open), br As New BinaryReader(fs)
Try
Catch ex As Exception
'an exception here indicates an issue reading the file
End Try
End Using
Catch ex As Exception
'an exception here indicates an issue opening the filestream or reader
End Try
The using block ensures that the objects are disposed of without the need to explicitly call .Dispose
it also calls .Close
so you don't even need that line
Upvotes: 1
Reputation: 1499860
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
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.Upvotes: 2