Convert.ToBoolean fails with "0" value
Solution 1
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
- Any non-
0
(numerical type; ...) =true
-
null
=false
Any other value is invalid for Boolean
.
You've already got a clean approach:
var myValue = Convert.ToBoolean(Convert.ToInt32("0"));
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
- Any other string =
true
Code:
public static class Extensions
{
public static Boolean ToBoolean(this string str)
{
String cleanValue = (str ?? "").Trim();
if (String.Equals(cleanValue, "False", StringComparison.OrdinalIgnoreCase))
return false;
return
(String.Equals(cleanValue, "True", StringComparison.OrdinalIgnoreCase)) ||
(cleanValue != "0");
}
}
Alternatively, if you want a more strict approach, which follows what the .NET Framework expects; then simply use try/catch
statements:
public static class Extensions
{
public static Boolean ToBoolean(this string str)
{
try
{
return Convert.ToBoolean(str);
}
catch { }
try
{
return Convert.ToBoolean(Convert.ToInt32(str));
}
catch { }
return false;
}
}
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:
String myString = "1";
Boolean myBoolean = myString.ToBoolean();
Solution 2
public static class BooleanParser
{
public static bool SafeParse(string value)
{
var s = (value ?? "").Trim().ToLower();
return s == "true" || s == "1";
}
}
static readonly HashSet<string> _booleanTrueStrings = new HashSet<string> { "true", "yes", "1" };
static readonly HashSet<string> _booleanFalseStrings = new HashSet<string> { "false", "no", "0" };
public static bool ToBoolean(string value)
{
var v = value?.ToLower()?.Trim() ?? "";
if (_booleanTrueStrings.Contains(v)) return true;
if (_booleanFalseStrings.Contains(v)) return false;
throw new ArgumentException("Unexpected Boolean Format");
}
Solution 3
Since it's really a matter of still doing those conversions and such, how about an extension method?
public static class Extensions {
public static bool ToBool(this string s) {
return s == "0" ? false : true;
}
}
and so then you would use it like this:
"0".ToBool();
and now you could easily extend this method to handle even more cases if you wanted.
Solution 4
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.
public bool ToBoolean(string value)
{
var boolValue = false;
if (bool.TryParse(value, out boolValue ))
{
return boolValue;
}
var number = 0;
int.TryParse(value, out number))
return Convert.ToBoolean(number);
}
Solution 5
Fast enough and simple:
public static class Extensions
{
static private List<string> trueSet = new List<string> { "true","1","yes","y" };
public static Boolean ToBoolean(this string str)
{
try
{ return trueSet.Contains(str.ToLower()); }
catch { return false; }
}
}
Related videos on Youtube
Secret
Updated on July 19, 2021Comments
-
Secret almost 3 years
I'm trying to convert the value
"0"
(System.String
) to itsBoolean
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
toBoolean
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?
-
Paul Kearney - pk about 11 yearsThe example you reference is showing that there are invalid strings that the ToBoolean() method will reject. In addition to "0", they show examples of "TrueString" and string.Empty. The sample is showing that these are invalid, not that you can actually use those values.
-
Bernhard over 7 yearswhy not use var res="1yestrue".Contains(yourVar)? There are also Boolean.Parse() / Boolean.TryParse() ?
-
super cool over 4 yearssimply use
Convert.ToInt32("0") > 0
which gives you bool .
- Is there any other way to convert to the
-
Secret about 11 yearstry to convert to the Boolean type the "0" as I said in the topic and look at the msdn sample on: msdn.microsoft.com/en-us/library/86hw82a3.aspx, you will get an excpetion with a try of converting the "0" string value.
-
Jesse about 11 yearsBecause
"0"
is not"True"
or"False"
. The only string representation accepted is"True"
or"False"
. -
Secret about 11 yearsyou have refreshed you answer :) first variant of it was different and hold the "0" in the list, so my comment was referenced to it, not the refreshed one :) also the cleanest approach does look ugly for code-style
-
Toan Vo about 11 yearsYou can use extension method to have the Parse Boolean as you wish. It will make your code clean and straight forward into convert boolean from string.
-
Jesse about 11 years@ToanVo Thanks for the tip; I've added some sample
Extensions
methods. -
Jesse about 11 years@OlegOrlov Glad this answer helped!
-
Secret about 11 years@Jesse thank you too for the great answer ;) I think, that such a question will be a good exercise for the students or a good test for the job interview. Just to make a Q in the test about such a problem and ask about solutions or possible exceptions.