I'm trying to convert the value "0"
( System.String
) to its Boolean
representation, like:
var myValue = Convert.ToBoolean("0"); // throwing an exception here
I've looked at the MSDN page, and in the code-sample block, I found these lines:
ConvertToBoolean("0");
// ...
Unable to convert '0' to a Boolean.
In my code, I'm converting from the System.String
to Boolean
like this:
// will be OK, but ugly code
var myValue = Convert.ToBoolean(Convert.ToInt32("0"));
- Is there any other way to convert to the
Boolean
type with not such ugly code? - Why does such an exception occur? Because of converting from the reference type
System.String
to the value type theSystem.Boolean
, butSystem.Int32
is also a value type, isn't it?
You can call it like following -:
Here's a very forgiving parser that keys off of the first character:
Fast enough and simple:
Since it's really a matter of still doing those conversions and such, how about an extension method?
and so then you would use it like this:
and now you could easily extend this method to handle even more cases if you wanted.
For a successful conversion to occur, the value parameter must equal either
Boolean.TrueString
, a constant whose value isTrue
,Boolean.FalseString
, a constant whose value isFalse
, or it must be null. In comparing value with Boolean.TrueString and Boolean.FalseString, the method ignores case as well as leading and trailing white space.from MSDN
because
Convert.ToBoolean
expects a true if value is not zero; otherwise, false. numerical value andTrue
orFalse
String
value.