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.