Converts string to Boolean, throws an exception if not compatible : bool « Data Types « C# / C Sharp






Converts string to Boolean, throws an exception if not compatible

  

using System;

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);
         }         
      }                                     
   }
}

   
    
  








Related examples in the same category

1.bool variable
2.A static method that returns a Boolean value.
3.Using BoolUsing Bool
4.Demonstrate bool valuesDemonstrate bool values
5.Print a truth table for the logical operatorsPrint a truth table for the logical operators
6.bool FalseString, TrueString
7.Convert boolean value to "Yes" or "No"
8.Convert string to Boolean. A return value indicates whether the conversion succeeded or failed.
9.Convert text values to boolean