The Essential .NET Data Types

  • 8/15/2011

The Boolean Data Type

The data type Boolean saves binary states, which means it doesn’t save much. Its value can be False or True—it can’t save anything else. This data type is most frequently used when running conditional program code (you saw the basics of conditional code in Chapter 1).

.NET data type: System.Boolean

Represents: One of two states: True or False.

Type literal: Not available

Memory requirements: 2 bytes

Note: To define a Boolean variable, use the keywords True and False directly and without quotes in the program text, such as in the following example:

Dim locBoolean As Boolean
locBoolean = True 'Expression is true.
locBoolean = False 'Expression is false.

Converting to and from Numeric Data Types

You can convert a Boolean type to a numeric data type.

The following example shows how this works:

Dim locInt As Integer = CInt(locBoolean)    ' locInt is -1
locInt = Convert.ToInt32(locBoolean)        ' locInt is now +1!!!
Dim locLong As Long = CLng(locBoolean)      ' locLong is -1
locLong = Convert.ToInt64(locBoolean)       ' locLong is +1

When converting it back, the behavior of the Convert class of .NET Framework and the conversion statements of Visual Basic are identicial. Only the numeric value 0 returns the Boolean result of False, all other values result in True, as the following example shows.

locBoolean = CBool(-1)                      ' locBoolean is True.
locBoolean = CBool(0)                       ' locBoolean is False.
locBoolean = CBool(1)                       ' locBoolean is True.
locBoolean = Convert.ToBoolean(-1)          ' locBoolean is True.
locBoolean = Convert.ToBoolean(+1)          ' locBoolean is True.
locBoolean = CBool(100)                     ' locBoolean is True.
locBoolean = Convert.ToBoolean(100)         ' locBoolean is True.

Converting to and from Strings

When you convert a Boolean data type into a string—for example, to save its status in a file—the respective value is converted to one of two strings represented by the static read-only properties TrueString and FalseString of the Boolean structure. In the current version of .NET Framework (4.0, as of this writing), they result in “True” and “False,” regardless of the computer’s cultural settings. So, no matter if your programs run on a United States platform or, for example, on a German platform, it always becomes either “True” or “False”, never “Wahr” or “Falsch”. When converting a String into Boolean, these strings return the values True and False, respectively.