string to bool inline conversion

asp.net, boolean, c#, string

Solution

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();

Problem

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`?

Original source