Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler warning: null reference exception

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

like image 620
RobS Avatar asked Nov 27 '08 11:11

RobS


3 Answers

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 C# error: Use of unassigned local variable

like image 126
tvanfosson Avatar answered Dec 11 '22 08:12

tvanfosson


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

like image 20
user40980 Avatar answered Dec 11 '22 08:12

user40980


The accepted answer is correct, of course, but it doesn't explain why or when explicit initialization may matter.

VB.NET usually assigns a default value (0 or Nothing) when a variable is declared, but there are corner cases where it doesn't.

Consider this simple console application:

Sub Main()
    For i As Integer = 1 To 5
        Dim number As Integer
        If i = 3 Then number = 3

        Console.Write(number)
    Next
End Sub

What's the output look like? You might expect that number gets set to 0 for every iteration of the loop, and it only gets set to 3 on the third iteration of the loop. Then for the fourth and fifth iteration, it'd be 0 again. So the output is 00300, right? Not so. The output of this code is actually

00333

That's because in VB.NET, the lifetime of a variable declared in a loop is for the whole loop, not for one iteration of the loop (Not what you'd expect, huh?). But if you explicitly set the value of number to 0 at its declaration, like so

Dim number As Integer = 0

then the output looks like

00300

So it's usually safe to assume VB.NET will set the default value when you Dim a variable, but it's always safest to set it explicitly to 0 or Nothing to get the expected behavior.

like image 24
Arin Avatar answered Dec 11 '22 06:12

Arin