Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToBoolean fails with "0" value

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 the System.Boolean, but System.Int32 is also a value type, isn't it?
like image 709
Secret Avatar asked Apr 25 '13 02:04

Secret


People also ask

How do you convert 1 and 0 to true and false?

Multiply original formula by 1 Note: You can also divide original formula by 1 or add 0 to original formula to change the return TRUE to 1 and FALSE to 0.

What is Convert ToBoolean?

ToBoolean(Object) Converts the value of a specified object to an equivalent Boolean value. ToBoolean(Decimal) Converts the value of the specified decimal number to an equivalent Boolean value. ToBoolean(Int32)

Is 0 true or false in C#?

A Boolean value occupies one byte of memory, as the following C# or F# example shows. The C# example must be compiled with the /unsafe switch. The byte's low-order bit is used to represent its value. A value of 1 represents true ; a value of 0 represents false .

How do you convert int to Boolean?

The Convert. ToBoolean() method converts an integer value to a boolean value in C#. In C#, the integer value 0 is equivalent to false in boolean, and the integer value 1 is equivalent to true in boolean.


2 Answers

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(); 
like image 89
Jesse Avatar answered Sep 23 '22 17:09

Jesse


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"); } 
like image 38
ChaosPandion Avatar answered Sep 21 '22 17:09

ChaosPandion