Visual Basic 2008 9.0 .NET Examples and Ebook
  Home

Procedures and Functions

Vorig Onderwerp

Arrays

|

Object Oriented Programming

Volgend Onderwerp

Static Variables

Vorig Onderwerp

Module Variables

|

Statementblcok Variables

Volgend Onderwerp
Exercise

Exercise



Static variables are declared within a routine, and can only be accessed from within that routine.

The variables are not removed from memory when the routine finishes. The lifespan of these variables equals the lifespan of the module ( in which they are declared ). Therefore static variables keep there values between different execution-instances of a routine.


Module Example1
    Sub Main()
        Test1()
        Test1()
        Test1()
        '
        Test2()
        Test2()
        Test2()
        '
        Console.ReadLine()
    End Sub
    Sub Test1()
        Static x As Integer
        x += 1
        Console.WriteLine(x)
    End Sub
    Sub Test2()
        Static x As Integer = 10
        x += 1
        Console.WriteLine(x)
    End Sub
End Module
Download Broncode

Output :

 1
 2
 3
 11
 12
 13

An initialization ( on the declaration line of a static variable ) is not repeated when the routine ( declaring the static variable ) is executed several times.

Static variables consume more ( or consume longer ) memory than local and argument variables, therefore limit the use of this type of variables.

Static variables are often used to let routines behave differently on different occasions.


Module Example2
    Sub Main()
        Test()
        Test()
        Test()
        '
        Console.ReadLine()
    End Sub
    Sub Test()
        Static firstExecution As Boolean = True
        If firstExecution Then
            Console.WriteLine("First execution of Test.")
            firstExecution = False
        Else
            Console.WriteLine("Not the first execution of Test.")
        End If
    End Sub
End Module
Download Broncode

Output :

 First execution of Test.
 Not the first execution of Test.
 Not the first execution of Test.

Exercise


Task :

What will be the output of module Exercise1Task ?


Module Exercise1Task
    Sub Main()
        Test1()
        Test1()
        '
        Console.ReadLine()
    End Sub
    Sub Test1()
        Static t1 As Integer = 10
        t1 += 1
        Test2(t1)
        Test2(t1)
    End Sub
    Sub Test2(ByVal t2 As Integer)
        Static t3 As Integer = 20
        t3 += t2
        Console.WriteLine(t3)
    End Sub
End Module
Download Broncode

Solution :


Output :

 31
 42
 54
 66

Updated On : 2008-11-06

Download Broncode

Published On : 2008-11-06

Static Variables

Vorig Onderwerp

Module Variables

|

Statementblcok Variables

Volgend Onderwerp

Procedures and Functions

Vorig Onderwerp

Arrays

|

Object Oriented Programming

Volgend Onderwerp
  Home  
Nederlands
Nederlands

Add to favorites (IE).


No printable version available.