Constants

Constants provide a way to represent an immutable value with an identifier. There could be situations in which your applications need to use the same value (which can be of any .NET type); therefore, it can be convenient to define an easy-to-remember identifier instead of a value. What would happen if such a value were a Long number? You declare constants as follows:

Const defaultIntegerValue As Integer = 123456789
Const aConstantString As String = "Same value along the application"

Constants are read-only fields that can be declared only at the module and class level or within a method and must be assigned with a value when declared. Constants within methods have public visibility by default, whereas constants at the module and class levels can have one of the .NET scopes, as in the following lines:

Private Const defaultIntegerValue As Integer = 123456789
Public Const aConstantString As String= "Same value along the application"

The reason constants must be assigned when declared is that the expression is evaluated at compile time. Starting from Visual Basic 2008, there are a couple of things to consider. Look at the following line of code:

Private Const Test = "Test message"

The type for the Test variable is not specified. Until Visual Basic 2005, with Option Strict Off, such a declaration would assign Object. In later versions of the language, if Option Infer is On, the compiler assigns String; if it is Off, the compiler goes back to assigning Object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181