20

If I have a variable that pulls a string of true or false from the DB,
which would be the preferred way of checking its value?

string value = "false";

if(Boolean.Parse(value)){
   DoStuff();
}

I know there are different ways of parsing to bool - this is an example
or

string value = "false";

if(value == "true"){
   DoStuff();
}

I am pulling a lot of true/false values from the DB in string format, and want to know if these methods make any performance difference at all?

2
  • 1
    Either method is fine but many developers will prefer Bool.TryParse(). The second method is a string comparison which will be slightly slower, o(n^2) Commented Aug 20, 2013 at 7:15
  • This question is similar to: how to convert a string to a bool. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Nov 10, 2024 at 11:42

8 Answers 8

46

Use Boolean.TryParse:

string value = "false";
Boolean parsedValue;

if (Boolean.TryParse(value, out parsedValue))
{
      if (parsedValue)
      {
         // do stuff
      }
      else
      {
         // do other stuff
      }
}
else
{
   // unable to parse
}
Sign up to request clarification or add additional context in comments.

5 Comments

Should the original if/else not be a try/catch ?
@NewAmbition: No, because TryParse returns true if the conversion was successful, false if it was unable to parse.
A shorthand alternative would be bool parsed = Boolean.TryParse(stringToParse, out parsedValue) && parsedValue;
@NewAmbition: Yes, it would be an alternative. But, if you use your alternative, you wouldn't be able to find out whether the conversion was successful. It would just return false if the conversion would be unsuccessful. If you use my code, you're able to find out whether the conversion was successful.
Well, if the conversion was unsuccessful, it would return false. I'm not trying to argue your point at all, but if a person just wants to get the result, you can do it with that ;) Your version allows the user to do 'whatever' after trying to convert.
7

The only issue I can see here is that C# does case sensitive comparisons, so if the database value was "True"

(value == "true")

would return false.

But looking at the example Boolean.Parse Method

string[] values = { null, String.Empty, "True", "False", 
                      "true", "false", "    true    ", "0", 
                      "1", "-1", "string" };
  foreach (var value in values) {
     try {
        bool flag = Boolean.Parse(value);
        Console.WriteLine("'{0}' --> {1}", value, flag);
     }
     catch (ArgumentException) {
        Console.WriteLine("Cannot parse a null string.");
     }   
     catch (FormatException) {
        Console.WriteLine("Cannot parse '{0}'.", value);
     }         
  }            

// The example displays the following output: 
//       Cannot parse a null string. 
//       Cannot parse ''. 
//       'True' --> True 
//       'False' --> False 
//       'true' --> True 
//       'false' --> False 
//       '    true    ' --> True 
//       Cannot parse '0'. 
//       Cannot parse '1'. 
//       Cannot parse '-1'. 
//       Cannot parse 'string'.

Bool.Parse seems a little bit more robust.

6 Comments

You should probably use string.Equals()
@SamLeach - I dont think that was the point of the exercise.. Secondly, should you not use TryParse in this case (Judging by the other answers?)
You should definitely use Boolean.TryParse() (see my answer) but if you're going to compare strings, you should use string.Equals() instead of ==. That was my point.
@SamLeach Since string's == operator just calls string.Equals(), why do you think you should use that instead? Would the same apply to using int.Equals() instead of ==?
@SamLeach We are not using an object in this example; we are using a string and therefore polymorphic differences do not apply. Thus, when using a string, Equals() and == are precisely the same.
|
4

I would always parse it - your application should be robust against invalid values (even if you "know" your database will always be valid):

bool myVal;
if (!Boolean.TryParse(value, out myVal))
{
    throw new InvalidCastException(...); // Or do something else
}

Comments

2

For sure use Boolean.TryParse(), you will avoid case-sensitive issues that can pop up.

2 Comments

Case-sensitivity I can see - but cultural issues?
@JonSkeet you are right, I was confused with my personal extension method that avoids cultural issues parsing boolean. Sometimes values can come up "translated" in the system culture (for example Vero-Falso in italian) depending on how they was written. I've updated the answer.
2

In C# 7.0+ you can use inline variable declaration.

string value = "false";

if (bool.TryParse(value, out bool parsedValue))
{
    if (parsedValue)
    {
        // do stuff
    }
    else
    {
        // do other stuff
    }
}
else
{
    // unable to parse
}

Comments

1

When asking for performance the version without parsing will probably be the faster one. But as others already suggested i also would prefer the parsing solution.

Comments

0

If you know the string will be a valid "true" or "false" string your first method is prefered.

Otherwise, you could use Boolean.TryParse

Comments

-1
string value = "your text"
bool outresult = false;
bool resultado = false;

resultado = bool.TryParse(value, out outresult);

The try parse function will try to convert the value of the string to boolean, if it can not return the value of the variable outresult.

1 Comment

This does not answer the question that was asked. Also please post to StackOverflow using English.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.