|
|
 |
|
|
|
|
Visual Basic 2008 9.0 .NET Examples and Ebook
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 ). |
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' ). |
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.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|