Declaring Constants and Literal Types

 

Dim myDecimal as Decimal
myDecimal = 100000000000000000000   ' This causes a compiler error.

 

The error results from the representation of the literal. The Decimal data type can hold a value this large, but the literal is implicitly represented as a Long, which cannot.

You can coerce a literal to a particular data type in two ways: by appending a type character to it, or by placing it within enclosing characters. A type character or enclosing characters must immediately precede and/or follow the literal, with no intervening space or characters of any kind.

To make the previous example work, you can append the D type character to the literal, which causes it to be represented as a Decimal:

MyDecimal = 100000000000000000000D

The following example demonstrates correct usage of type characters and enclosing characters:

Option Strict Off
Public Const DefaultInteger = 100   ' Default is Integer.
Public Const DefaultDouble = 54.3345612   ' Default is Double.
Public Const MyCharacter = "a"C   ' Forces constant to be a Char type.
Public Const MyDate = #01/15/01#   ' Demonstrates DateTime constants.
Public Const MyTime = #1:15:59 AM#
Public Const MyLong = 45L   ' Forces data type to be a Long.
Public Const MySingle = 45.55!   ' Forces data type to be a Single.

The following table shows the enclosing characters and type characters available in Visual Basic.

Data type Enclosing character Appended type character
Boolean (none) (none)
Byte (none) (none)
Char " C
Date # (none)
Decimal (none) D or @
Double (none) R or #
Integer (none) I or %
Long (none) L or &
Short (none) S
Single (none) F or !
String " (none)