Convert::ToBoolean Method (String^)

 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

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 Boolean::TrueString or Boolean::FalseString.

Return Value

Type: System::Boolean

true if value equals TrueString, or false if value equals FalseString or null.

Exception Condition
FormatException

value is not equal to TrueString or FalseString.

For a successful conversion to occur, the value parameter must equal either Boolean::TrueString, a constant whose value is True, Boolean::FalseString, a 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 namespace System;

void main()
{
   array<String^>^ values = gcnew array<String^> { nullptr, String::Empty,
                                                   "true", "TrueString",
                                                   "False", "    false    ",
                                                   "-1", "0" };
   for each (String^ value in values) {
      try
      {
         Console::WriteLine("Converted '{0}' to {1}.", value,  
                           Convert::ToBoolean(value));
      }
      catch (FormatException^ e)
      {
         Console::WriteLine("Unable to convert '{0}' to a Boolean.", value);
      }
   }
}
// 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.

Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
Show: