Formatting Boolean values

The string representation of a Boolean is either "True" for a true value or "False" for a false value. The string representation of a Boolean value is defined by the read-only TrueString and FalseString fields.

You use the ToString method to convert Boolean values to strings. The Boolean structure includes two ToString overloads: the parameterless ToString() method and the ToString(IFormatProvider) method, which includes a parameter that controls formatting. However, because this parameter is ignored, the two overloads produce identical strings. The ToString(IFormatProvider) method does not support culture-sensitive formatting.

Because the Boolean structure can have only two values, it is easy to add custom formatting. For simple custom formatting in which other string literals are substituted for "True" and "False", you can use any conditional evaluation feature supported by your language, such as the conditional operator in C# or the If operator in Visual Basic. The following example uses this technique to format Boolean values as "Yes" and "No" rather than "True" and "False".

Imports System.Globalization
Module Example
Public Sub Main()
Dim cultureNames() As String = { "", "en-US", "fr-FR", "ru-RU" }
For Each cultureName In cultureNames
Dim value As Boolean = True
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(cultureName)
Dim formatter As New BooleanFormatter(culture)
Dim result As String = String.Format(formatter, "Value for '{0}': {1}", culture.Name, value)
Console.WriteLine(result)
Next
End Sub
End Module
Public Class BooleanFormatter
Implements ICustomFormatter, IFormatProvider
Private culture As CultureInfo
Public Sub New()
Me.New(CultureInfo.CurrentCulture)
End Sub
Public Sub New(culture As CultureInfo)
Me.culture = culture
End Sub
Public Function GetFormat(formatType As Type) As Object _
Implements IFormatProvider.GetFormat
If formatType Is GetType(ICustomFormatter) Then
Return Me
Else
Return Nothing
End If
End Function
Public Function Format(fmt As String, arg As Object,
formatProvider As IFormatProvider) As String _
Implements ICustomFormatter.Format
' Exit if another format provider is used.
If Not formatProvider.Equals(Me) Then Return Nothing
' Exit if the type to be formatted is not a Boolean
If Not TypeOf arg Is Boolean Then Return Nothing
Dim value As Boolean = CBool(arg)
Select culture.Name
Case "en-US"
Return value.ToString()
Case "fr-FR"
If value Then
Return "vrai"
Else
Return "faux"
End If
Case "ru-RU"
If value Then
Return "верно"
Else
Return "неверно"
End If
Case Else
Return value.ToString()
End Select
End Function
End Class
' The example displays the following output:
' Value for '': True
' Value for 'en-US': True
' Value for 'fr-FR': vrai
' Value for 'ru-RU': верно

Optionally, you can use resource files to define culture-specific Boolean strings.

Converting to and from Boolean values

The Boolean structure implements the IConvertible interface. As a result, you can use the Convert class to perform conversions between a Boolean value and any other primitive type in the .NET Framework, or you can call the Boolean structure's explicit implementations. However, conversions between a Boolean and the following types are not supported, so the corresponding conversion methods throw an InvalidCastException exception:

All conversions from integral or floating-point numbers to Boolean values convert non-zero values to true and zero values to false. The following example illustrates this by calling selected overloads of the Convert.ToBoolean class.

When converting from floating-point values to Boolean values, the conversion methods perform an exact comparison with zero. If the floating-point value has lost precision, the result can be unexpected. This is illustrated in the following example, in which a Double variable whose value should be zero is converted to a Boolean value. As the example shows, the result is true because repeated additions of 0.2 have resulted in a loss of precision.

When converting from Boolean to numeric values, the conversion methods of the Convert class convert true to 1 and false to 0. However, Visual Basic conversion functions convert true to either 255 (for conversions to Byte values) or -1 (for all other numeric conversions). The following example converts true to numeric values by using a Convert method, and, in the case of the Visual Basic example, by using the Visual Basic language's own conversion operator.

Parsing Boolean values

The Boolean structure includes two static parsing methods, Parse and TryParse, that convert a string to a Boolean value. The string representation of a Boolean value is defined by the case-insensitive equivalents of the values of the TrueString and FalseString fields, which are "True" and "False", respectively. In other words, the only strings that parse successfully are "True", "False", "true", "false", or some mixed-case equivalent. You cannot successfully parse numeric strings such as "0" or "1". Leading or trailing white-space characters are not considered when performing the string comparison.

The following example uses the Parse and TryParse methods to parse a number of strings. Note that only the case-insensitive equivalents of "True" and "False" can be successfully parsed.

If you are programming in Visual Basic, you can use the CBool function to convert the string representation of a number to a Boolean value. "0" is converted to false, and the string representation of any non-zero value is converted to true. If you are not programming in Visual Basic, you must convert your numeric string to a number before converting it to a Boolean. The following example illustrates this by converting an array of integers to Boolean values.

Comparing Boolean values

Because Boolean values are either true or false, there is little reason to explicitly call the CompareTo method, which indicates whether an instance is greater than, less than, or equal to a specified value. Typically, to compare two Boolean variables, you call the Equals method or use your language's equality operator.

However, when you want to compare a Boolean variable with the literal Boolean value true or false, it is not necessary to do an explicit comparison, because the result of evaluating a Boolean value is that Boolean value. For example, the expressions

The following example calls the BitConverter.GetBytes method to convert a Boolean value to its binary representation and displays the individual bits of the value, and then calls the BitConverter.ToBoolean method to restore the value from its binary representation.

Performing operations with Boolean values

This section illustrates how Boolean values are used in apps. The first section discusses its use as a flag. The second illustrates its use for arithmetic operations.

Boolean values as flags

Boolean variables are most commonly used as flags, to signal the presence or absence of some condition. For example, in the String.Compare(String, String, Boolean) method, the final parameter, ignoreCase, is a flag that indicates whether the comparison of two strings is case-insensitive (ignoreCase is true) or case-sensitive (ignoreCase is false). The value of the flag can then be evaluated in a conditional statement.

The following example uses a simple console app to illustrate the use of Boolean variables as flags. The app accepts command-line parameters that enable output to be redirected to a specified file (the /f switch), and that enable output to be sent both to a specified file and to the console (the /b switch). The app defines a flag named isRedirected to indicate whether output is to be sent to a file, and a flag named isBoth to indicate that output should be sent to the console.

Imports System.IO
Imports System.Threading
Module Example
Public Sub Main()
' Initialize flag variables.
Dim isRedirected, isBoth As Boolean
Dim fileName As String = ""
Dim sw As StreamWriter = Nothing
' Get any command line arguments.
Dim args() As String = Environment.GetCommandLineArgs()
' Handle any arguments.
If args.Length > 1 Then
For ctr = 1 To args.Length - 1
Dim arg As String = args(ctr)
If arg.StartsWith("/") OrElse arg.StartsWith("-") Then
Select Case arg.Substring(1).ToLower()
Case "f"
isRedirected = True
If args.Length < ctr + 2 Then
ShowSyntax("The /f switch must be followed by a filename.")
Exit Sub
End If
fileName = args(ctr + 1)
ctr += 1
Case "b"
isBoth = True
Case Else
ShowSyntax(String.Format("The {0} switch is not supported",
args(ctr)))
Exit Sub
End Select
End If
Next
End If
' If isBoth is True, isRedirected must be True.
If isBoth And Not isRedirected Then
ShowSyntax("The /f switch must be used if /b is used.")
Exit Sub
End If
' Handle output.
If isRedirected Then
sw = New StreamWriter(fileName)
If Not IsBoth Then
Console.SetOut(sw)
End If
End If
Dim msg As String = String.Format("Application began at {0}", Date.Now)
Console.WriteLine(msg)
If isBoth Then sw.WriteLine(msg)
Thread.Sleep(5000)
msg = String.Format("Application ended normally at {0}", Date.Now)
Console.WriteLine(msg)
If isBoth Then sw.WriteLine(msg)
If isRedirected Then sw.Close()
End Sub
Private Sub ShowSyntax(errMsg As String)
Console.WriteLine(errMsg)
Console.WriteLine()
Console.WriteLine("Syntax: Example [[/f <filename> [/b]]")
Console.WriteLine()
End Sub
End Module

Booleans and arithmetic operations

A Boolean value is sometimes used to indicate the presence of a condition that triggers a mathematical calculation. For example, a hasShippingCharge variable might serve as a flag to indicate whether to add shipping charges to an invoice amount.

Because an operation with a false value has no effect on the result of an operation, it is not necessary to convert the Boolean to an integral value to use in the mathematical operation. Instead, you can use conditional logic.

The following example computes an amount that consists of a subtotal, a shipping charge, and an optional service charge. The hasServiceCharge variable determines whether the service charge is applied. Instead of converting hasServiceCharge to a numeric value and multiplying it by the amount of the service charge, the example uses conditional logic to add the service charge amount if it is applicable.

Booleans and interop

While marshaling base data types to COM is generally straightforward, the Boolean data type is an exception. You can apply the MarshalAsAttribute attribute to marshal the Boolean type to any of the following representations:

A 4-byte integer value, where any nonzero value represents true and 0 represents false. This is the default format of a Boolean field in a structure and of a Boolean parameter in platform invoke calls.

Applies to

Thread Safety

All members of this type are thread safe. Members that appear to modify instance state actually return a new instance initialized with the new value. As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

Feedback

We'd love to hear your thoughts. Choose the type you'd like to provide: