Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to bool inline conversion

What I currently have:

bool okPress = !string.IsNullOrEmpty(Ctx.Request["okPress"]) &&
    Convert.ToBoolean(Ctx.Request["okPress"]);

Correct me if I'm wrong here, but wouldn't this throw a FormatException if the string isn't "true/True" or "false/False"? Is there any way to handle the conversion in one row, without having to worry about exceptions? Or do I need to use Boolean.TryParse?

like image 645
Johan Avatar asked Apr 02 '13 10:04

Johan


2 Answers

You can use Boolean.TryParse:

bool okPress;
bool success = Boolean.TryParse(Ctx.Request["okPress"]), out okPress);

For what it's worth, here a "one-liner", create following extension which might be useful especially in LINQ queries:

public static bool TryGetBool(this string item)
{
    bool b;
    Boolean.TryParse(item, out b);
    return b; 
}

and write:

bool okPress = Ctx.Request["okPress"].TryGetBool();
like image 62
Tim Schmelter Avatar answered Sep 28 '22 08:09

Tim Schmelter


IF you didn't want to use TryParse You could do something like

bool okPress = !string.IsNullOrEmpty(Ctx.Request["okPress"]) &&
(Ctx.Request["okPress"].ToLower()=="true");

This way if the string is not true/false it will just assume false for you with no exceptions thrown.

This does of course assume that you are happy for a value of "fish" to be treated as false rather than as an exception.

Better though is to just not do it as a single line. You don't generally have a maximum number of lines of code so two or three simple lines of code are often better than one complicated line of code...

like image 29
Chris Avatar answered Sep 28 '22 08:09

Chris