views:

390

answers:

2

I have the following code in Visual Studio 2005.

    Dim OutFile As System.IO.StreamWriter
    Try
        OutFile = New System.IO.StreamWriter(Filename)
       // Do stuff with OutFile
    Catch Ex As Exception
       // Handle Exception
    Finally
       If OutFile IsNot Nothing Then OutFile.Close()
    End Try

But VS2005 brings up the warning for the line "If OutFile IsNot.." that

Variable 'OutFile' is used before it has been assigned a value. A null reference exception could result at runtime.

Is there some way of removing this warning by subtly altering the code or is there just a better way of doing what I'm trying to do?

Thanks

Rob

+6  A: 
Dim OutFile As System.IO.StreamWriter
OutFile = Nothing
Try
    OutFile = New System.IO.StreamWriter(Filename)
   // Do stuff with OutFile
Catch Ex As Exception
   // Handle Exception
Finally
   If OutFile IsNot Nothing Then OutFile.Close()
End Try

Similar to http://stackoverflow.com/questions/256073/c-error-use-of-unassigned-local-variable#256078

tvanfosson
Nearly, but it pointed me in the right direction. NULL isn't allowed but Outfile = Nothing does the trick. Thanks.
RobS
Just noticed it and fixed it. I usually program in c# if you couldn't guess.
tvanfosson
:) It's nice to have a warning-less project. Thanks again.
RobS
So we have to use an assignment to avoid the warning...? Seems pretty stupid, especially because you are assigning it to nothing, which means the same warning should still exists becuase the null reference could still occur. This is dumb! VS should not even waste its time trying to figure out if my code is going to give a null reference; there must be a way to disable this warning.
Josh Stodola
Not really. It's not trying to prevent the null reference but the accidental omission of a default value. Forcing you to explicitly provide a default to remove the warning makes you aware that you have left the variable potentially undefined.
tvanfosson
+1  A: 

Its a question of scope, the initialisation of the outfile object is happening in a block of code not visible to the fianlly block.