Convert string to Boolean, throws an exception if not compatible in CSharp

Description

The following code shows how to convert string to Boolean, throws an exception if not compatible.

Example


using System;/*ww w.  j a v a2 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) {
         try {
            bool flag = Boolean.Parse(value);
            Console.WriteLine("'{0}' --> {1}", value, flag);
         }
         catch (ArgumentException) {
            Console.WriteLine("Cannot parse a null string.");
         }   
         catch (FormatException) {
            Console.WriteLine("Cannot parse '{0}'.", 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