18

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?

TheGeekZn
  • 3,696
  • 10
  • 55
  • 91
  • 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) – Gusdor Aug 20 '13 at 07:15

8 Answers8

44

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
}
ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
  • Should the original if/else not be a try/catch ? – TheGeekZn Aug 20 '13 at 07:18
  • 2
    @NewAmbition: No, because `TryParse` returns true if the conversion was successful, false if it was unable to parse. – ProgramFOX Aug 20 '13 at 07:19
  • 13
    A shorthand alternative would be `bool parsed = Boolean.TryParse(stringToParse, out parsedValue) && parsedValue;` – TheGeekZn Aug 20 '13 at 07:30
  • 2
    @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. – ProgramFOX Aug 20 '13 at 07:31
  • 1
    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. – TheGeekZn Aug 20 '13 at 07:35
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.

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
  • You should probably use string.Equals() – Sam Leach Aug 20 '13 at 07:17
  • @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?) – TheGeekZn Aug 20 '13 at 07:24
  • 1
    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. – Sam Leach Aug 20 '13 at 07:33
  • 1
    @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 `==`? – Matthew Watson Aug 20 '13 at 08:04
  • Jon Skeet says otherwise http://stackoverflow.com/questions/3678792/are-string-equals-and-operator-really-same – Sam Leach Aug 20 '13 at 08:07
  • 1
    @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. – Matthew Watson Aug 20 '13 at 10:00
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
}
Ant P
  • 24,820
  • 5
  • 68
  • 105
2

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

Tobia Zambon
  • 7,479
  • 3
  • 37
  • 69
  • 4
    Case-sensitivity I can see - but cultural issues? – Jon Skeet Aug 20 '13 at 07:19
  • 1
    @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. – Tobia Zambon Aug 20 '13 at 07:26
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.

LunicLynx
  • 939
  • 1
  • 8
  • 16
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

Sam Leach
  • 12,746
  • 9
  • 45
  • 73
0

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
}
Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116
-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.