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?
To convert String to boolean in Java, you can use Boolean. parseBoolean(string). But if you want to convert String to Boolean object then use the method Boolean. valueOf(string) method.
Boolean parseBoolean() method in Java with examples Parameters: It takes one parameter value of type string which contains the value which is to be converted to boolean. Return Value: It returns a primitive boolean value. It returns the true if the given value is equals “true” ignoring cases. Else it returns false.
Syntax: public static bool TryParse (string value, out bool result);
parseBoolean(String s) − This method accepts a String variable and returns boolean. If the given string value is "true" (irrespective of its case) this method returns true else, if it is null or, false or, any other value it returns false.
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With