Convert.ToBoolean("1") leads to exceptions

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top