Improved block-scoping rules.
- Dominant language
- No language data
- Stars
- 328
- Forks
- 71
- PR merge metrics
- No merged PRs in 30d
Description
I don't remember exactly when VB got block-scoping, but I've loved every minute of it. However there some cases that can be quite confusing:
```vb
Do
Dim CompletedCount = 0
For n = 1 To MyTaskCount
If SomeTaskCompleted(n) Then
CompletedCount += 1
End If
Next
Loop While CompletedCount > 1 '<-- compiler says `CompletedCount` is not declared.
```
In the above code, the variable `CompletedCount` is declared inside the `Do...Loop While` block and naturally scoped to that block. But strangely enough, the comparison expression in the `Loop While` clause can't access that variable even though the expression is part of the Loop block itself.
Another scenario is the `Try` statement:
```vb
Try
Dim SomeResource = GetTheResource()
DoStuffThatCouldThrowException()
Finally
'compiler says SomeResource is not declared in this block.
If SomeResource IsNot Nothing Then
SomeResource.Close()
End If
End Try
```
The `Finally` block is very much a part of the entire `Try...Finally...End Try` block but you can't access the variables declared inside the `Try` block itself.
In both the above cases, you have to declare the variable **outside** the `Try...End Try` and `Do...Loop While` blocks, and when you do that, it "leaks out" beyond the scope where it is intended.
Could we improve this? I am thinking two rules would help:
1. Variables declared inside a block, are accessible in all clauses of that block, which can contain expressions (this would fix the `Do...Loop While` case above).
2. Variables declared inside earlier blocks of a multi-block statement are accessible in later blocks of the multi-block statement, unless those later blocks declare a variable with the same name (this would fix the `Try...Finally...End Try` case above).
CC: @AnthonyDGreen
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.