Scope in VB.net

By: Steven Holzner Emailed: 1672 times Printed: 2153 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

The scope of an element in your code is all the code that can refer to it without qualifying its name (or making it available through an Imports statement). In other words, an element's scope is its accessibility in your code. As we write larger programs, scope will become more important, because we'll be dividing code into classes, modules, procedures, and so on. You can make the elements in those programming constructs private, which means they are tightly restricted in scope.

In VB .NET, where you declare an element determines its scope, and an element can have scope at one of the following levels:

  • Block scope—available only within the code block in which it is declared

  • Procedure scope—available only within the procedure in which it is declared

  • Module scope—available to all code within the module, class, or structure in which it is declared

  • Namespace scope—available to all code in the namespace

For example, if you declare a variable in a module outside of any procedure, it has module scope, as in this case, where I'm declaring and creating a LinkLabel control that has module scope:

Dim LinkLabel1 As LinkLabel

Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
    LinkLabel1 = New LinkLabel()
    LinkLabel1.AutoSize = True
    LinkLabel1.Location = New Point(15, 15)
        
Tip 

When you want to declare module-level variables, you can place the declaration outside any procedure in the module. You also can select the module in the left-hand drop-down list box in the code designer and the (Declarations) item in the right-hand drop-down box, which will take you to a location at the very beginning of the module, outside any procedure.

Declaring a variable in a procedure gives it procedure scope, and so on. Inside these levels of scope, you can also specify the scope of an element when you declare it. Here are the possibilities in VB .NET:

  • Public —The Public statement declares elements to be accessible from anywhere within the same project, from other projects that reference the project, and from an assembly built from the project. You can use Public only at module, namespace, or file level. This means you can declare a Public element in a source file or inside a module, class, or structure, but not within a procedure.

  • Protected —The Protected statement declares elements to be accessible only from within the same class, or from a class derived from this class. You can use Protected only at class level, and only when declaring a member of a class.

  • Friend —The Friend statement declares elements to be accessible from within the same project, but not from outside the project. You can use Friend only at module, namespace, or file level. This means you can declare a Friend element in a source file or inside a module, class, or structure, but not within a procedure.

  • Protected Friend —The Protected statement with the Friend keyword declares elements to be accessible either from derived classes or from within the same project, or both. You can use Protected Friend only at class level, and only when declaring a member of a class.

  • Private —The Private statement declares elements to be accessible only from within the same module, class, or structure. You can use Private only at module, namespace, or file level. This means you can declare a Private element in a source file or inside a module, class, or structure, but not within a procedure.

Let's take a look at an example. Here's what block scope looks like—in this case, I'll declare a variable, strText in an If statement. That variable can be used inside the If statement's block, but not outside (VB .NET will tag the second use here as a syntax error):

Module Module1
    Sub Main()
        Dim intValue As Integer = 1
        If intValue = 1 Then
            Dim strText As String = "No worries."
            System.Console.WriteLine(strText)
        End If
        System.Console.WriteLine(strText)          'Will not work!
    End Sub
End Module

Here's another example. In this case, I've created a second module, Module2, and defined a function, Function1, in that module. To make it clear that I want to be able to access Function1 outside Module2 (as when I call it as Module2. Function1 in the Main procedure), I declare Function1 public:

Module Module1
    Sub Main()
        System.Console.WriteLine(Module2.Function1())
    End Sub
End Module

Module Module2
    Public Function Function1() As String 'OK
        Return "Hello from Visual Basic"
    End Function
End Module
Tip 

Note that in this case, I've put Module2 into the same file as Module1. You can also create a new file for Module2 if you prefer—just select Project|Add New Item and then select Module in the Templates box of the Add New Item dialog that opens.

However, if I declared Function1 as private to Module2, it's inaccessible in Module1 (and VB .NET will tag Module2.Function1 below as a syntax error):

Module Module1
    Sub Main()
        System.Console.WriteLine(Module2.Function1())   'Will not work!
    End Sub
End Module

Module Module2
    Private Function Function1() As String
        Return "Hello from Visual Basic"
    End Function
End Module

Besides procedures, you also can make other elements—such as variables—public or private. Here, I'm declaring strData as public in Module2 to make it clear that I want to access it outside the module, which I can do in Module1, referring to strData as Module2.strData:

Module Module1
    Sub Main()
        System.Console.WriteLine(Module2.strData)
    End Sub
End Module
Module Module2
    Public strData As String = "Hello from Visual Basic"
End Module

In fact, when you declare elements like strData public throughout the program, you need not qualify their names in other code, so I can refer to strData in Module1 as well:

Module Module1
    Sub Main()
        System.Console.WriteLine(strData)
    End Sub
End Module

Module Module2
    Public strData As String = "Hello from Visual Basic"
End Module

Now that VB .NET is object-oriented, understanding scope is more important. In object-oriented programming, scope becomes a major issue, because when you create objects, you often want keep the data and code in those objects private from the rest of the program. Scope also becomes an issue when you derive one OOP class from another


VB.net Home | All VB.net Tutorials | Latest VB.net Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Steven Holzner
Changes in Controls from VB6 to VB.net
Throwing a Custom Exception in VB.net
Throwing an Exception in VB.net
Using Finally in VB.net
Using Multiple Catch Statements in VB.net
Exception Filtering in the Catch Block in VB.net
Raising an Exception Intentionally in VB.net
Getting an Exception's Number and Description in VB.net
Using On Error GoTo 0 in VB.net
Using Resume Next and Resume Line in VB.net
Understanding Scope in VB.net
Properties in VB.net
Procedure Delegates in VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Specifying Optional Arguments with default values in Procedures in VB.net

More Tutorials in VB.net
Scope in VB.net
Unstructured Exception Handling in VB.net
Structured Exception Handling in VB.net
Creating Sub Procedures in VB.net
Creating Functions in VB.net
Passing a Variable Number of Arguments to Procedures in VB.net
Specifying Optional Arguments with default values in Procedures in VB.net
Preserving a Variable's Values between Procedure Calls in VB.net
Procedure Delegates in VB.net
Properties in VB.net
Understanding Scope in VB.net
Using Resume Next and Resume Line in VB.net
Using On Error GoTo 0 in VB.net
Getting an Exception's Number and Description in VB.net
Raising an Exception Intentionally in VB.net

More Latest News
Most Viewed Articles (in VB.net )
Your first VB.NET Crystal Reports - A step by step guide
How to export from DataGridView to excel using VB.net
The Option and Imports Statements in VB .NET
Operators in VB.net
How To Connect To A MySql Database in VB.net
A tutorial on Chat Server and Chat Client in VB.net
Creating Tree Views in Code using VB.net
Using Resume Next and Resume Line in VB.net
Arrays and Dynamic Arrays in VB.net
Sub Procedures and Functions in VB.net
Using Excel 2007 Chart in VB.NET 2005
Insert cell data in an Excel file using OLEDB in VB.net
How to read URL Content through VB.net code
Passing a Variable Number of Arguments to Procedures in VB.net
Specifying Optional Arguments with default values in Procedures in VB.net
Most Emailed Articles (in VB.net)
Send SMS using VB code
How to export from database to excel using VB.net
String equals, Copy to & Copy to in VB.net
A tutorial on Chat Server and Chat Client in VB.net
String.Contains (), compare, clone in VB.net
Your first VB.NET Crystal Reports - A step by step guide
Socket Programming in VB.net
Handling Timer Events - and Creating an Alarm Clock in VB.net
File Extensions Used in VB .NET
Using Select Case in VB.net
For Loop in VB.net
How To Connect To A MySql Database in VB.net
Stack data structure in VB.net
String Split function in VB.net
Create an Excel 2007 file in VB.NET 2005