Try to parse string to Boolean in CSharp

Description

The following code shows how to try to parse string to Boolean.

Example


using System;//from   w  w w . j a va  2  s. c o m

public class Example
{
   public static void Main()
   {
      string[] values = { "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);
         else
            Console.WriteLine("Unable to parse '{0}'.", 
                              value == null ? "<null>" : value);
      }                                     
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var