Convert.ToBoolean("1") leads to exceptions

  • Thread starter Thread starter clive
  • Start date Start date
C

clive

from MSDN
http://msdn.microsoft.com/library/d...nconvertingstringstonetframeworkdatatypes.asp

String to Boolean

The following table shows what type is generated for the given input
strings, when converting a string to Boolean using the ToBoolean
method.
Valid string input parameter .NET Framework output type
"true" Boolean.True
"1" Boolean.True
"false" Boolean.False
"0" Boolean.False

Now my immediate window tells me a different story

?convert.ToBoolean("1")
Run-time exception thrown : System.FormatException - String was not
recognized as a valid Boolean.
?boolean.Parse("1")
Run-time exception thrown : System.FormatException - String was not
recognized as a valid Boolean.
?convert.ToBoolean(convert.ToInt16("1"))
True
?boolean.Parse("true")
True
?boolean.Parse("True")
True
?boolean.Parse("TrUe")
True

So my code now has an if else to handle this.

If columnValue.Length = 1 Then ' for 0 and 1
Return Convert.ToBoolean(Convert.ToInt16(columnValue))
Else ' for TRUE and FALSE
Return Convert.ToBoolean(columnValue)
End If

Is there something I'm doing wrong here?
 
Back
Top