Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Convert.ToBoolean(string) and Boolean.Parse(string)?

What is the difference between the two methods

Convert.ToBoolean()

and

Boolean.Parse()?

Is there any reason to use one or the other?

Additionally, are there any other type.Parse() methods that I should watch out for?

Thanks,

Matt

like image 389
mbrownnyc Avatar asked Aug 11 '11 19:08

mbrownnyc


People also ask

What is ToBoolean?

ToBoolean(Object) Converts the value of a specified object to an equivalent Boolean value. ToBoolean(Decimal) Converts the value of the specified decimal number to an equivalent Boolean value. ToBoolean(Int32)

Is bool parse case insensitive?

The value parameter, optionally preceded or trailed by white space, must contain either TrueString or FalseString; otherwise, an exception is thrown. The comparison is case-insensitive.

How do you use bool TryParse?

open System let values = [ null; String. Empty; "True"; "False" "true"; "false"; " true "; "0" "1"; "-1"; "string" ] for value in values do match Boolean. TryParse value with | true, flag -> printfn $"'{value}' --> {flag}" | false, _ -> printfn $"""Unable to parse '%s{if value = null then "<null>" else value}'.


1 Answers

Convert.ToBoolean(string) actually calls bool.Parse() anyway, so for non-null strings, there's no functional difference. (For null strings, Convert.ToBoolean() returns false, whereas bool.Parse() throws an ArgumentNullException.)

Given that fact, you should use bool.Parse() when you're certain that your input isn't null, since you save yourself one null check.

Convert.ToBoolean() of course has a number of other overloads that allow you to generate a bool from many other built-in types, whereas Parse() is for strings only.

In terms of type.Parse() methods you should look out for, all the built-in numeric types have Parse() as well as TryParse() methods. DateTime has those, as well as the additional ParseExact()/TryParseExact() methods, which allow you specify an expected format for the date.

like image 95
dlev Avatar answered Sep 17 '22 14:09

dlev