C# – FormatException 0 is not a valid value for Boolean

.netc++

I am getting a formatexception with the following code. Any one know how to make BooleanConverter convert from 0/1 to true/false.

 bool bVal=true;
 string sVal = "0";
 Console.WriteLine(TypeDescriptor.GetConverter(bVal).ConvertFrom(sVal));

Thanks for the help!

Best Solution

Try the following

public static bool ConvertToBasedOnIntValue(string value) {
  // error checking omitted for brevity
  var i = Int32.Parse(value);
  return value == 0 ? false : true;
}

Or you could use the following which won't throw exceptions but it will consider everything that is quite literally not 0 to be true

public static bool ConvertToBasedOnIntValue(string value) {
  if ( 0 == StringComparer.CompareOrdinal(value, "0") ) {
    return false;
  }
  return true;
}