Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET - Block level scope

Tags:

vb.net

Please have a look at the code below:

Public Class TestClass
    Public TestProperty As Integer
End Class

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, 
                           ByVal e As System.EventArgs) Handles Me.Load
        Dim i As Integer
        Dim j As Integer
        For j = 0 To 2
            For i = 0 To 10
                Dim k As Integer
                Dim tc As TestClass
                tc = New TestClass
                tc.TestProperty = tc.TestProperty + 1
                k = k + 1
            Next
        Next
    End Sub
End Class

There is a new object (called tc) created on every iteration of the FOR loop, so tc.TestProperty is always 1. Why is this not the case with variable k i.e. the value of k increments by one on every iteration? I realise this is probably to do with how value types and reference types are dealt with, but I wanted to check.

like image 613
w0051977 Avatar asked Mar 05 '26 02:03

w0051977


1 Answers

It's because when something is defined as block level it applies to the entire block level, regardless of loops. normally with control logic like an IF block statement the scope starts and ends and no code lines repeat.

Inside a loop structure the variable is defined inside that block, even though the Dim statement appears to be called multiple times it is not, it is not actually an executable statement (just a definition and reservation of a placeholder as mentioned above in one comment)

To cause it to behave in the same way as "tc" you also need to initialize it in a similar way. (the assignment to 0 would occur each loop, not the definition)

Dim k As Integer = 0

Alternately if you change how your dealing with tc it would behave the same way as k where it is in block scope the entire time inside the loop. In the below example tc is not redefined each loop either.

Dim tc as TestClass
if tc is nothing then tc = New TestClass
like image 67
DarrenMB Avatar answered Mar 08 '26 20:03

DarrenMB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!