ToBoolean Method (String)

Convert.ToBoolean Method (String)

[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]

Converts the specified String representation of a logical value to its Boolean equivalent.

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

public static bool ToBoolean(
	string value
)

Parameters

value
Type: System.String
A String that contains the value of either TrueString or FalseString.

Return Value

Type: System.Boolean
true if value equals TrueString, or false if value equals FalseString or null.

ExceptionCondition
FormatException

value is not equal to TrueString or FalseString.

For a successful conversion to occur, the value parameter must equal either Boolean.TrueString, a string constant whose value is True, Boolean.FalseString, a string constant whose value is False, or it must be null. In comparing value with Boolean.TrueString and Boolean.FalseString, the method ignores case as well as leading and trailing white space.

If you prefer not to handle an exception if the conversion fails, you can call the Boolean.TryParse method instead. It returns a Boolean value that indicates whether the conversion succeeded or failed.

The following example uses the Convert.ToBoolean(String) method to convert various strings to Boolean values.


using System;

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      ConvertToBoolean(outputBlock, null);
      ConvertToBoolean(outputBlock, String.Empty);
      ConvertToBoolean(outputBlock, "true");
      ConvertToBoolean(outputBlock, "TrueString");
      ConvertToBoolean(outputBlock, "False");
      ConvertToBoolean(outputBlock, "    false    ");
      ConvertToBoolean(outputBlock, "-1");
      ConvertToBoolean(outputBlock, "0");
   }

   private static void ConvertToBoolean(System.Windows.Controls.TextBlock outputBlock, string value)
   {
      try
      {
         outputBlock.Text += String.Format("Converted '{0}' to {1}.", value,
                           Convert.ToBoolean(value)) + "\n";
      }
      catch (FormatException)
      {
         outputBlock.Text += String.Format("Unable to convert '{0}' to a Boolean.", value) + "\n";
      }
   }
}
// The example displays the following output:
//       Converted '' to False.
//       Unable to convert '' to a Boolean.
//       Converted 'true' to True.
//       Unable to convert 'TrueString' to a Boolean.
//       Converted 'False' to False.
//       Converted '    false    ' to False.
//       Unable to convert '-1' to a Boolean.
//       Unable to convert '0' to a Boolean.


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2017 Microsoft