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?
This is happening because
Convert.ToBoolean
is expecting one of the following:"True"
(String) =true
"False"
(String) =false
0
(numerical type; int, double, float, etc.) =false
0
(numerical type; ...) =true
null
=false
Any other value is invalid for
Boolean
.You've already got a clean approach:
Edit: You can create an extension method that will handle a few of these cases for you, while hiding away the ugliness of handling the conversion.
This extension provides a very loose interpretation of
Boolean
:"True"
(String) =true
"False"
(String) =false
"0"
(String) =false
true
Code:
Alternatively, if you want a more strict approach, which follows what the .NET Framework expects; then simply use
try/catch
statements:Albeit, not a clean or pretty approach, but it guarantees more possibilities of getting the correct value. And, the
Extensions
class is tucked away from your data/business code.In the end, your conversion code is relatively simple to use:
If you know that it would be an int then you can convert it to int then to bool. Following will try for conversion to bool by attempting the string then attempting with number.