Why bool.try does not parse TRUE or FALSE

Please consider the following code.

bool somevariable; bool.TryParse(Convert.ToString(Dataset.Tables[0].Rows[0]["SomeColumnName"]), out somevariable); CheckBox.Checked = somevariable; 

In "SomeColumnName" in the dataset, I have a value of 1. Therefore, I assume that it will parse this 1 as TRUE in "somevariable".

But when I try to parse this value on bool, it always returns as false.

I do not know why.

+4
source share
4 answers

From the Boolean.Parse documentation:

true if the value is equal to the value of the Boolean.TrueString field; false if the value is equal to the value of the Boolean.FalseString field.

1 and 0 not equivalent to "true" or "false" .

Assuming your SomeColumnName indeed a boolean field, you can do:

 return Convert.ToString(Dataset.Tables[0].Rows[0]["SomeColumnName"]) == "1"; 

Or directly convert to boolean (thanks @Bolu):

 return Convert.ToBoolean(Dataset.Tables[0].Rows[0]["SomeColumnName"]); 
+10
source

Here is my routine, which is in a file shared by many projects:

  /// <summary> /// Legal values: Case insensitive strings TRUE/FALSE, T/F, YES/NO, Y/N, numbers (0 => false, non-zero => true) /// Similar to "bool.TryParse(string text, out bool)" except that it handles values other than 'true'/'false' and handles numbers like C/C++ /// </summary> public static bool TryParseBool(object inVal, out bool retVal) { // There are a couple of built-in ways to convert values to boolean, but unfortunately they skip things like YES/NO, 1/0, T/F //bool.TryParse(string, out bool retVal) (.NET 4.0 Only); Convert.ToBoolean(object) (requires try/catch) inVal = (inVal ?? "").ToString().Trim().ToUpper(); switch ((string)inVal) { case "TRUE": case "T": case "YES": case "Y": retVal = true; return true; case "FALSE": case "F": case "NO": case "N": retVal = false; return true; default: // If value can be parsed as a number, 0==false, non-zero==true (old C/C++ usage) double number; if (double.TryParse((string)inVal, out number)) { retVal = (number != 0); return true; } // If not a valid value for conversion, return false (not parsed) retVal = false; return false; } } 
+5
source

Taken from MSDN

When this method returns, if the conversion is successful, it contains true if the value is Boolean.TrueString or false if the value is equivalent to FalseString. If the conversion fails, it contains false. The conversion fails if the value is null or not equivalent to the value of the TrueString or FalseString field.

1 not equivalent to Boolean.TrueString ( "true" or any case), so the conversion is not performed ( TryParse returns false ), and the out parameter (in this case somevariable ) is set to default(bool) , which is false .

+3
source

If "1" is a string, it will not parse it as a boolean true. If it is "true" as a string, then it will parse it as a boolean true.

+1
source

Source: https://habr.com/ru/post/1395390/


All Articles