Johan
Johan

Reputation: 35223

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?

Upvotes: 5

Views: 2655

Answers (5)

Tim Schmelter
Tim Schmelter

Reputation: 460360

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

Upvotes: 5

MeTitus
MeTitus

Reputation: 3428

Your inline conversion.

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

        bool.TryParse(expression, out booleanValue);

        return booleanValue;
    }

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

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98868

You can use TryParse method of Boolean class as you said.

Tries to convert the specified string representation of a logical value to its Boolean equivalent. A return value indicates whether the conversion succeeded or failed.

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

It returns true if value was converted successfully; otherwise, false.

Upvotes: 1

Konamiman
Konamiman

Reputation: 50323

Why don't you compare the string against true?

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

Upvotes: 1

Chris
Chris

Reputation: 27627

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...

Upvotes: 2

Related Questions