Export (0) Print
Expand All

Boolean Structure

Represents a Boolean (true or false) value.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct Boolean : IComparable, IConvertible, 
	IComparable<bool>, IEquatable<bool>

The Boolean type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsCompareTo(Boolean)Compares this instance to a specified Boolean object and returns an integer that indicates their relationship to one another.
Public methodSupported by the XNA FrameworkCompareTo(Object)Compares this instance to a specified object and returns an integer that indicates their relationship to one another.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Boolean)Returns a value indicating whether this instance is equal to a specified Boolean object.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Returns a value indicating whether this instance is equal to a specified object. (Overrides ValueType.Equals(Object).)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeReturns the hash code for this instance. (Overrides ValueType.GetHashCode().)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodSupported by the XNA FrameworkGetTypeCodeReturns the TypeCode for value type Boolean.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsParseConverts the specified string representation of a logical value to its Boolean equivalent, or throws an exception if the string is not equal to the value of Boolean.TrueString or Boolean.FalseString.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToString()Converts the value of this instance to its equivalent string representation (either "True" or "False"). (Overrides ValueType.ToString().)
Public methodSupported by the XNA FrameworkToString(IFormatProvider)Converts the value of this instance to its equivalent string representation (either "True" or "False").
Public methodStatic memberSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryParseTries to convert the specified string representation of a logical value to its Boolean equivalent. A return value indicates whether the conversion succeeded or failed.
Top

  NameDescription
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFalseStringRepresents the Boolean value false as a string. This field is read-only.
Public fieldStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsTrueStringRepresents the Boolean value true as a string. This field is read-only.
Top

  NameDescription
Explicit interface implemetationPrivate methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsIComparable.CompareToInfrastructure. Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToBooleanInfrastructure. For a description of this member, see IConvertible.ToBoolean.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToByteInfrastructure. For a description of this member, see IConvertible.ToByte.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToCharInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToDateTimeInfrastructure. This conversion is not supported. Attempting to use this method throws an InvalidCastException.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToDecimalInfrastructure. For a description of this member, see IConvertible.ToDecimal..
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToDoubleInfrastructure. For a description of this member, see IConvertible.ToDouble..
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToInt16Infrastructure. For a description of this member, see IConvertible.ToInt16.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToInt32Infrastructure. For a description of this member, see IConvertible.ToInt32.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToInt64Infrastructure. For a description of this member, see IConvertible.ToInt64.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToSByteInfrastructure. For a description of this member, see IConvertible.ToSByte.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToSingleInfrastructure. For a description of this member, see IConvertible.ToSingle..
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToTypeInfrastructure. For a description of this member, see IConvertible.ToType.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToUInt16Infrastructure. For a description of this member, see IConvertible.ToUInt16.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToUInt32Infrastructure. For a description of this member, see IConvertible.ToUInt32.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkIConvertible.ToUInt64Infrastructure. For a description of this member, see IConvertible.ToUInt64.
Top

A Boolean instance can have either of two values: true, or false.

The Boolean structure provides methods that support the following tasks:

The following sections explain these tasks and other usage details:

Formatting Boolean values
Converting to and from Boolean values
Parsing Boolean values
Comparing Boolean values
Working with Booleans as binary values
Performing operations with Boolean values

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.

The following example illustrates formatting with the ToString method. Note that the example uses the composite formatting feature, so the ToString method is called implicitly.

using System;

public class Example
{
   public static void Main()
   {
      bool raining = false;
      bool busLate = true;

      Console.WriteLine("It is raining: {0}", raining);
      Console.WriteLine("The bus is late: {0}", busLate);
   }
}
// The example displays the following output: 
//       It is raining: False 
//       The bus is late: True

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".

using System;

public class Example
{
   public static void Main()
   {
      bool raining = false;
      bool busLate = true;

      Console.WriteLine("It is raining: {0}", 
                        raining ? "Yes" : "No");
      Console.WriteLine("The bus is late: {0}", 
                        busLate ? "Yes" : "No" );
   }
}
// The example displays the following output: 
//       It is raining: No 
//       The bus is late: Yes

For more complex custom formatting operations, including culture-sensitive formatting, you can call the String.Format(IFormatProvider, String, Object[]) method and provide an ICustomFormatter implementation. The following example implements the ICustomFormatter and IFormatProvider interfaces to provide culture-sensitive Boolean strings for the English (United States), French (France), and Russian (Russia) cultures.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      String[] cultureNames = { "", "en-US", "fr-FR", "ru-RU" };
      foreach (var cultureName in cultureNames) {
         bool value = true;
         CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
         BooleanFormatter formatter = new BooleanFormatter(culture);

         String result = String.Format(formatter, "Value for '{0}': {1}", culture.Name, value);
         Console.WriteLine(result);
      }
   }
}

public class BooleanFormatter : ICustomFormatter, IFormatProvider
{   
   private CultureInfo culture;

   public BooleanFormatter() : this(CultureInfo.CurrentCulture)
   { }

   public BooleanFormatter(CultureInfo culture)
   {
      this.culture = culture; 
   }

   public Object GetFormat(Type formatType)
   { 
      if (formatType == typeof(ICustomFormatter))
         return this;
      else 
         return null;
   }

   public String Format(String fmt, Object arg, IFormatProvider formatProvider)
   { 
      // Exit if another format provider is used. 
      if (! formatProvider.Equals(this)) return null;

      // Exit if the type to be formatted is not a Boolean 
      if (! (arg is Boolean)) return null;

      bool value = (bool) arg;
      switch (culture.Name) {
         case "en-US":
            return value.ToString();
         case "fr-FR":
            if (value) 
               return "vrai";
            else 
               return "faux";
         case "ru-RU":
            if (value)
               return "верно";
            else 
               return "неверно";
         default:
            return value.ToString();  
      }
   }
}
// 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.

using System;

public class Example
{
   public static void Main()
   {
      Byte byteValue = 12;
      Console.WriteLine(Convert.ToBoolean(byteValue));
      Byte byteValue2 = 0;
      Console.WriteLine(Convert.ToBoolean(byteValue2));
      int intValue = -16345;
      Console.WriteLine(Convert.ToBoolean(intValue));
      long longValue = 945;
      Console.WriteLine(Convert.ToBoolean(longValue));
      SByte sbyteValue = -12;
      Console.WriteLine(Convert.ToBoolean(sbyteValue));
      double dblValue = 0;
      Console.WriteLine(Convert.ToBoolean(dblValue));
      float sngValue = .0001f;
      Console.WriteLine(Convert.ToBoolean(sngValue));
   }
}
// The example displays the following output: 
//       True 
//       False 
//       True 
//       True 
//       True 
//       False 
//       True

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.

using System;

public class Example
{
   public static void Main()
   {
      bool flag = true;

      byte byteValue;   
      byteValue = Convert.ToByte(flag);
      Console.WriteLine("{0} -> {1}", flag, byteValue);         

      sbyte sbyteValue;
      sbyteValue = Convert.ToSByte(flag);
      Console.WriteLine("{0} -> {1}", flag, sbyteValue);         

      double dblValue;
      dblValue = Convert.ToDouble(flag);
      Console.WriteLine("{0} -> {1}", flag, dblValue);         

      int intValue;
      intValue = Convert.ToInt32(flag);
      Console.WriteLine("{0} -> {1}", flag, intValue);         
   }
}
// The example displays the following output: 
//       True -> 1 
//       True -> 1 
//       True -> 1 
//       True -> 1

For conversions from Boolean to string values, see the Formatting Boolean Values section. For conversions from strings to Boolean values, see the Parsing Boolean Values section.

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.

using System;

public class Example
{
   public static void Main()
   {
      string[] values = { null, String.Empty, "True", "False", 
                          "true", "false", "    true    ", 
                           "TrUe", "fAlSe", "fa lse", "0",  
                          "1", "-1", "string" };
      // Parse strings using the Boolean.Parse method.                     
      foreach (var value in values) {
         try {
            bool flag = Boolean.Parse(value);
            Console.WriteLine("'{0}' --> {1}", value, flag);
         }
         catch (ArgumentException) {
            Console.WriteLine("Cannot parse a null string.");
         }   
         catch (FormatException) {
            Console.WriteLine("Cannot parse '{0}'.", value);
         }         
      }
      Console.WriteLine();
      // Parse strings using the Boolean.TryParse method.                     
      foreach (var value in values) {
         bool flag = false;
         if (Boolean.TryParse(value, out flag))
            Console.WriteLine("'{0}' --> {1}", value, flag);
         else
            Console.WriteLine("Unable to parse '{0}'", value);
      }                                     
   }
}
// The example displays the following output: 
//       Cannot parse a null string. 
//       Cannot parse ''. 
//       'True' --> True 
//       'False' --> False 
//       'true' --> True 
//       'false' --> False 
//       '    true    ' --> True 
//       'TrUe' --> True 
//       'fAlSe' --> False 
//       Cannot parse 'fa lse'. 
//       Cannot parse '0'. 
//       Cannot parse '1'. 
//       Cannot parse '-1'. 
//       Cannot parse 'string'. 
//        
//       Unable to parse '' 
//       Unable to parse '' 
//       'True' --> True 
//       'False' --> False 
//       'true' --> True 
//       'false' --> False 
//       '    true    ' --> True 
//       'TrUe' --> True 
//       'fAlSe' --> False 
//       Cannot parse 'fa lse'. 
//       Unable to parse '0' 
//       Unable to parse '1' 
//       Unable to parse '-1' 
//       Unable to parse 'string'

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.

using System;

public class Example
{
   public static void Main()
   {
      String[] values = { "09", "12.6", "0", "-13 " };
      foreach (var value in values) {
         bool success, result;
         int number; 
         success = Int32.TryParse(value, out number);
         if (success) {
            // The method throws no exceptions.
            result = Convert.ToBoolean(number);
            Console.WriteLine("Converted '{0}' to {1}", value, result);
         }
         else {
            Console.WriteLine("Unable to convert '{0}'", value); 
         }         
      }
   }
}
// The example displays the following output: 
//       Converted '09' to True 
//       Unable to convert '12.6' 
//       Converted '0' to False 
//       Converted '-13 ' to True

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

if (booleanValue) {

and

using System;

public class Example
{
   public static void Main()
   {
      bool[] hasServiceCharges = { true, false };
      Decimal subtotal = 120.62m;
      Decimal shippingCharge = 2.50m;
      Decimal serviceCharge = 5.00m;

      foreach (var hasServiceCharge in hasServiceCharges) {
         Decimal total = subtotal + shippingCharge + 
                                (hasServiceCharge ? serviceCharge : 0);
         Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.", 
                           total, hasServiceCharge);                       
      }
   }
}
// The example displays output like the following: 
//       hasServiceCharge = True: The total is $128.12. 
//       hasServiceCharge = False: The total is $123.12.

are equivalent, but the second is more compact. However, both techniques offer comparable performance.

Working with Booleans as binary values

A Boolean value occupies one byte of memory. The byte's low-order bit is used to represent its value. A value of 1 represents true; a value of 0 represents false.

Caution noteCaution

You can use the System.Collections.Specialized.BitVector32 structure to work with sets of Boolean values.

You can convert a Boolean value to its binary representation by calling the BitConverter.GetBytes(Boolean) method. The method returns a byte array with a single element. To restore a Boolean value from its binary representation, you can call the BitConverter.ToBoolean(Byte[], Int32) method.

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.

using System;

public class Example
{
   public static void Main()
   {
      bool[] flags = { true, false };
      foreach (var flag in flags) {
         // Get binary representation of flag.
         Byte value = BitConverter.GetBytes(flag)[0];
         Console.WriteLine("Original value: {0}", flag);
         Console.WriteLine("Binary value:   {0} ({1})", value, 
                           GetBinaryString(value));
         // Restore the flag from its binary representation. 
         bool newFlag = BitConverter.ToBoolean( new Byte[] { value }, 0);
         Console.WriteLine("Restored value: {0}\n", flag);
      }
   }

   private static string GetBinaryString(Byte value)
   {
      String retVal = Convert.ToString(value, 2);
      return new String('0', 8 - retVal.Length) + retVal;
   }
}
// The example displays the following output: 
//       Original value: True 
//       Binary value:   1 (00000001) 
//       Restored value: True 
//        
//       Original value: False 
//       Binary value:   0 (00000000) 
//       Restored value: False

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 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.

using System;
using System.IO;
using System.Threading;

public class Example
{
   public static void Main()
   {
      // Initialize flag variables. 
      bool isRedirected = false;
      bool isBoth = false; 
      String fileName = "";
      StreamWriter sw = null;

      // Get any command line arguments.
      String[] args = Environment.GetCommandLineArgs();
      // Handle any arguments. 
      if (args.Length > 1) { 
         for (int ctr = 1; ctr < args.Length; ctr++) {
            String arg = args[ctr];
            if (arg.StartsWith("/") || arg.StartsWith("-")) {
               switch (arg.Substring(1).ToLower())
               {
                  case "f":
                     isRedirected = true;
                     if (args.Length < ctr + 2) {
                        ShowSyntax("The /f switch must be followed by a filename.");
                        return;
                     }
                     fileName = args[ctr + 1];
                     ctr++;
                     break;
                  case "b":
                     isBoth = true;
                     break;
                  default:
                     ShowSyntax(String.Format("The {0} switch is not supported", 
                                              args[ctr]));
                     return;
               }
            }   
         }
      }

      // If isBoth is True, isRedirected must be True. 
      if (isBoth &&  ! isRedirected) { 
         ShowSyntax("The /f switch must be used if /b is used.");
         return;
      }

      // Handle output. 
      if (isRedirected) {
         sw = new StreamWriter(fileName); 
         if (!isBoth)
            Console.SetOut(sw); 
      }     
      String msg = String.Format("Application began at {0}", DateTime.Now);
      Console.WriteLine(msg);
      if (isBoth) sw.WriteLine(msg);
      Thread.Sleep(5000);
      msg = String.Format("Application ended normally at {0}", DateTime.Now);
      Console.WriteLine(msg);
      if (isBoth) sw.WriteLine(msg);
      if (isRedirected) sw.Close();
   }

   private static void ShowSyntax(String errMsg)
   {
      Console.WriteLine(errMsg);
      Console.WriteLine("\nSyntax: Example [[/f <filename> [/b]]\n");
   }
}

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.

using System;

public class Example
{
   public static void Main()
   {
      bool[] hasServiceCharges = { true, false };
      Decimal subtotal = 120.62m;
      Decimal shippingCharge = 2.50m;
      Decimal serviceCharge = 5.00m;

      foreach (var hasServiceCharge in hasServiceCharges) {
         Decimal total = subtotal + shippingCharge + 
                                (hasServiceCharge ? serviceCharge : 0);
         Console.WriteLine("hasServiceCharge = {1}: The total is {0:C2}.", 
                           total, hasServiceCharge);                       
      }
   }
}
// The example displays output like the following: 
//       hasServiceCharge = True: The total is $128.12. 
//       hasServiceCharge = False: The total is $123.12.

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

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.

Show:
© 2014 Microsoft