Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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.

Posted (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 by IceAzul

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...