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

后端 未结 3 1448
北恋
北恋 2020-12-11 00:16

What is the difference between the two methods

Convert.ToBoolean()

and

Boolean.Parse()?

Is there any reason to u

3条回答
  •  萌比男神i
    2020-12-11 00:58

    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.

提交回复
热议问题