String to bool inline conversion

I currently have:

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

Correct me if I am wrong here, but would not choose it FormatExceptionif the line is not " true/ true" or " false/ false"? Is there a way to handle the conversion on a single line without worrying about exceptions? Or do I need to use Boolean.TryParse?

+5
source share
5 answers

You can use Boolean.TryParse:

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

For what is "single-line" worthwhile, create the following extension, which can 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();
+5
source

IF you didn’t want to use TryParseyou could do something like

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

, /, false - .

, , , , "" , .

. , , ...

+2

true?

bool okPress = !string.IsNullOrEmpty(Ctx.Request["okPress"]) &&
    String.Compare(Ctx.Request["okPress"], "true", StringComparison.OrdinalIgnoreCase) == 0
+1

TryParse Boolean, .

. , .

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

true, ; false.

+1

.

    public static bool TryParseAsBoolean(this string expression)
    {
        bool booleanValue;

        bool.TryParse(expression, out booleanValue);

        return booleanValue;
    }

    bool okPress =  Ctx.Request["okPress"].TryParseAsBoolean();
0

All Articles