user72311
user72311

Reputation: 23

VB.NET variable scope

Are variables declared in a case statement local to that case statement -

For example, in the following code, is it safe to use z like this? Or is the compiler just placing z at the procedure scope?


        Select Case x
            Case 6
                Dim z As Integer = 6
            Case 7
                Dim z As Integer = 7
        End Select

Upvotes: 2

Views: 1103

Answers (1)

Spencer Ruport
Spencer Ruport

Reputation: 35107

It's safe to do that. You can test it by trying to compile the following:

Dim x As Integer
Select Case x
    Case 6
        Dim z As Integer = 6
    Case 7
        Dim z As Integer = 7
End Select
Console.Write(z)

And noting that you'll get a compile error.

Of course it cuts down on readability IMO. Maybe you should declare it at the beginning of the procedure anyway.

Upvotes: 3

Related Questions