I have the following code in Visual Studio 2005.
Dim OutFile As System.IO.StreamWriter
Try
OutFile = New System.IO.StreamWriter(Filename)
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.
Its a question of scope, the initialisation of the outfile object is happening in a block of code not visible to the fianlly block.
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