What is the scope of a block level variable in VB.NET?

Consider the following code:

For i As Integer = 0 To 10
   Dim str As String = str & " Kratika "
Next

      

When I attach a debugger and check the value str

for i = 10

, I see the following:

 Kratika  Kratika  Kratika  Kratika  Kratika  Kratika  Kratika  Kratika  Kratika  Kratika  Kratika 

      

Why does it combine the previous meaning? I would expect the variable to be set for kratika

every time, because every time it declares a new String object, right?

+3


source to share


2 answers


This is expected behavior.

As you noted in a comment on another answer, it might be easier to see the use of integers rather than string concatenation:

Sub Main()
  For i As Integer = 0 To 5
     Dim j As Integer = j + 1
     Console.WriteLine(j.ToString())
  Next
End Sub

      

The output looks like this:



1
2
3
4
5
6

      

To find out why, go to the documentation, in particular the scope section . The variable j

you declared is in block scope because it is declared inside the block For

. However, variables declared in block scope still retain their values ​​throughout their contained procedure. As the documentation says:

Even if the scope of a variable is limited to a block, its lifetime still depends on the entire procedure. If you enter a block more than once during a procedure, each block variable retains its previous value. To avoid unexpected results in such a case, it is advisable to initialize block variables at the beginning of the block.

So what happens is, every time you re-enter a block For

, j

it still has its previous meaning. Since the right side of the equal sign is evaluated first, the old value is j

incremented by 1 and then stored in j

(effectively deleting the old content j

).

+4


source


Hi you have a use str & " Kratika "

inside a loop. If you only expect it " Kratika "

every time. Then only use Dim str As String = " Kratika "

inside the loop.



Now check again

0


source







All Articles