This documentation is archived and is not being maintained.

Boolean.TryParse Method

Updated: September 2010

Tries to convert the specified string representation of a logical value to its Boolean equivalent. A return value indicates whether the conversion succeeded or failed.

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

public static bool TryParse(
	string value,
	out bool result


Type: System.String

A string containing the value to convert.

Type: System.Boolean%

When this method returns, if the conversion succeeded, contains true if value is equivalent to Boolean.TrueString or false if value is equivalent to FalseString. If the conversion failed, contains false. The conversion fails if value is null or is not equivalent to the value of either the TrueString or FalseString field.

Return Value

Type: System.Boolean
true if value was converted successfully; otherwise, false.

The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails.

The value parameter can be preceded or followed by white space. The comparison is case-insensitive.

The following example calls the TryParse method to parse an array of strings. Note that the parse operation succeeds only if the string to be parsed is "True" (the value of the TrueString field) or "False" (the value of the FalseString field) in a case-insensitive comparison.

using System;

public class Example
   public static void Main()
      string[] values = { null, String.Empty, "True", "False", 
                          "true", "false", "    true    ", "0", 
                          "1", "-1", "string" };
      foreach (var value in values) {
         bool flag;
         if (Boolean.TryParse(value, out flag))
            Console.WriteLine("'{0}' --> {1}", value, flag);
            Console.WriteLine("Unable to parse '{0}'.", 
                              value == null ? "<null>" : value);
// The example displays the following output: 
//       Unable to parse '<null>'. 
//       Unable to parse ''. 
//       'True' --> True 
//       'False' --> False 
//       'true' --> True 
//       'false' --> False 
//       '    true    ' --> True 
//       Unable to parse '0'. 
//       Unable to parse '1'. 
//       Unable to parse '-1'. 
//       Unable to parse 'string'.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

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

.NET Framework

Supported in: 3.5, 3.0, 2.0




September 2010

Replaced example.

Customer feedback.