JDYoder Posted August 17, 2005 Posted August 17, 2005 I understand the scope of a variable remains within its block of code. For instance, this var cannot be access outside the If block... If [Condition] Dim i As Integer ... End If Same with a loop like this... While [Condition] Dim i As Integer ... End While However, I'm wondering if the second example is bad practice. I like having it declared within the block since that's the only place it's used. However, since it's in a looping block, I'm wondering if the var is created and destructed on every pass, and I should instead declare it before the loop. Thanks for your input. Quote
IceAzul Posted August 17, 2005 Posted August 17, 2005 (edited) The variable is created on the stack when you enter the function. What you have here is a scope issue. Outside the loop, the code cannot access that particular variable. Lets say you have a function like this: Sub A() Dim X As Integer For X = 0 to 100 Dim Y As Integer Next End Sub At the beginning of the function, both X and Y are created. This is only true of value types(such as Integer, Byte, etc), however. If you are doing this with Reference types (such as StringBuilders, ArrayLists, etc), it will create a new object each time, and thus should be avoided. Edited August 17, 2005 by IceAzul Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.