Visual Basic 2008 9.0 .NET Examples and Ebook

Introduction to Visual Basic

Vorig Onderwerp

New in Visual Basic 2008 - 9.0

|

Arrays

Volgend Onderwerp

Constants

Vorig Onderwerp

Datatypes

|

Introduction to Arrays

Volgend Onderwerp
What are Constants

What are Constants

An Example

An Example

When Use Constants

When Use Constants



What are Constants


Just like variables, constants are "dataholders". They can be used to store data that is needed at runtime.

In contrast to variable, the content of a constant can't change at runtime, it has a constant value.
At compiletime the value for a constant must be known. The declaration line of the constant must contain an initialization clause ( where a constant expression ( for instance a literal ) is used to represent the initial value ).


Klik hier om terug naar boven te gaan.  Up



An Example


Module Example1
    Sub Main()
        Const pi As Double = 3.1415
        '
        Dim radius As Single = 10
        '
        Dim circumference As Double = radius * 2 * pi
        Dim area As Double = radius ^ 2 * pi
        '
        Console.WriteLine("Circle Circumference : " & circumference)
        Console.WriteLine("Circle Area          : " & area)
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 Circle Circumference : 62,83
 Circle Area          : 314,15

The above example declares a constant pi. We could have used a variable for pi, but because this value will never change during runtime, a constant was more appropriate. We protect ourself form accidentally changing this value.

It has to be said that a constant like 'pi' doesn't have to be declared. The FCL ( "Framework Class Library" ) already contains a constant for this value ( 'Math.PI' ).


Klik hier om terug naar boven te gaan.  Up



When Use Constants


Often constants are used to have an easy-to-remember name to refer to a difficult-to-remember value.


Module Example2
    Sub Main()
        Const red As Integer = &HFF0000
        Const green As Integer = &HFF00
        Const blue As Integer = &HFF
        '
        Console.WriteLine("red    : " & red)
        Console.WriteLine("green  : " & green)
        Console.WriteLine("blue   : " & blue)
        '
        Const purple As Integer = red + blue
        '
        Console.WriteLine("purple : " & purple)
        '
        '
        Console.ReadLine()
    End Sub
End Module
Download Broncode

Output :

 red    : 16711680
 green  : 65280
 blue   : 255
 purple : 16711935




This version ( published on 2008-06-24 ) is printed from http://www.studyvb.com, visit the website for more recent information.

Updated On : 2008-01-23

Download Broncode

Published On : 2008-06-24

Constants

Vorig Onderwerp

Datatypes

|

Introduction to Arrays

Volgend Onderwerp

Introduction to Visual Basic

Vorig Onderwerp

New in Visual Basic 2008 - 9.0

|

Arrays

Volgend Onderwerp
Nederlands  Nederlands

Add to favorites (IE).