Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block-scope for local variable

Tags:

scope

vb.net

Is there a better way to create an arbitrary block in VB.Net to limit the scope of a local variable? If have tried "If 1 Then", but it just looks kludgy.

If 1 Then
    Dim table = InputParameter1
    Dim new_row = table.AddRow
    new_row.field(1) = InputParameter3.user_value
End If

I just don't want to have table and new_row accessible later in the procedure.

like image 236
positivesigner Avatar asked Dec 06 '12 17:12

positivesigner


2 Answers

Re-factor your procedure so there's another procedure in which table and new_row do their thing. If you really don't need them to be visible later on, then they are doing a distinct sub-task that should be refactored anyway.

Generally speaking, when you can partition your code into N segments, where each segment has no dependency on the others, then you are looking at N tasks and preferably N procedures.

This goes back to the rule that any procedure should do one thing, and multiple segments are a sign that it's doing more than one thing.

like image 88
RonaldBarzell Avatar answered Oct 04 '22 06:10

RonaldBarzell


With Option Strict On, that'd have to be If True Then, but the more preferred option (as far as I have seen) is Do ... Loop While False.

But, no there is no syntax like a simple Begin ... End (or { ...}).

If you can work with an IDisposable, and have it disposed at the end of the block, Using newVariable = AnIDisposable gives you the closest to what you're describing, but like I said, it is disposed at the end.

like image 23
Mark Hurd Avatar answered Oct 04 '22 08:10

Mark Hurd