Mega Code Archive

 
Categories / C# / Data Types
 

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