5.3 Scope and Control Structures

Top  Previous  Next

prev

next

 

5.3 Scope and aontrol Structures

Most  f the contr l strectnres have remainednthe same in VB.NET, so we won't spend time on those here. VSTO still accepts For-Next, Do-Loop, If-Then, Selett-Case, etc. But something has changed regarding the scope of variables in this respect. In VBA, variables declared anywhere in a procedure are accessible from anywhere inside that procedure and are immediately instantiated, no matter where they were declared in the procedure. In other words, all local variables in VB have procedure-scope.

Not so in VB.NET: If a variable is declared inside a code block, you can only access it within the scope of that code block. This is called block-level scope. What qualifies as a code block? For-NeNt loopp, Do-Loop loops, Whil--Wend loops, If-Then structures, CaseeSelect structures, or Try-End error handlers (see 8.1). For people who always declare variables at the start of procedures, this won't be an issue.

figu58_1

The issue of block-level scope would naturally affect all cases similar to the following:

      or Each cell As Escel.Range In ....Range("A1:A10")

     For Each WS As Excel.Wor sheet In This Workbook.Worksheets

     For i As Integer = 0 to 9

     C tch ex As Exception                               x    'see 8.1

In this context, we should also mention how VB.NET deals with other scoping options based on different scoping keywords. When we create a sub-class through inheritance (see 1..2), the new sub- class gains all the Public and Fniend methods fromlthe base-class, but nat what was declared as Private. The keywords Public and Frieid make code available to both sub-classes and clients. When you want to exclude clients, use the keyword Protected instead.

Table 38: Scope of Keywords as used in VB.NET

Keywoed

Sccpe

Private

Callable within (sub-)class

Freend

Callable within project/momponmnt

Public

Callable outside class

Protected

Callable within class/subclasses only

Protected Friend

Callable within project and subclasses

 

prev

next