Convert.ToBoolean Method (String, IFormatProvider)

Converts the specified String representation of a logical value to its Boolean equivalent using the specified culture-specific formatting information.

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

public static bool ToBoolean(
	string value,
	IFormatProvider provider
)

Parameters

value
Type: System.String
A string that contains the value of either TrueString or FalseString.
provider
Type: System.IFormatProvider
(Reserved) An IFormatProvider interface implementation that supplies culture-specific formatting information.

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.

provider is ignored; it does not participate in this operation.

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 code sample illustrates the use of ToBoolean, taking a String parameter.


public void ConvertStringBoolean(string stringVal)
{
   bool boolVal = false;

   try
   {
      boolVal = System.Convert.ToBoolean(stringVal);
      if (boolVal)
      {
         outputBlock.Text += String.Format(
            "String was equal to System.Boolean.TrueString.") + "\n";
      }
      else
      {
         outputBlock.Text += String.Format(
            "String was equal to System.Boolean.FalseString.") + "\n";
      }
   }
   catch (System.FormatException)
   {
      outputBlock.Text += String.Format(
         "The string must equal System.Boolean.TrueString " +
         "or System.Boolean.FalseString.") + "\n";
   }

   // A conversion from bool to string will always succeed.
   stringVal = System.Convert.ToString(boolVal);
   outputBlock.Text += String.Format("{0} as a string is {1}",
      boolVal, stringVal) + "\n";
}


Windows Phone OS

Supported in: 8.1, 8.0, 7.1, 7.0

Windows Phone

Show:
© 2015 Microsoft