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
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
Here is the short demo:
Note: There are also two properties of
bool
TrueString and FalseString, but be careful, becausebool.TrueString != "true"
, onlybool.TrueString == "True"
Boolean.Parse()
will convert a string representation of a logical boolean value to a boolean value.Convert.ToBoolean()
has multiple overloads that will convert primitive types to their boolean equivalent.Most, if not all, of the primitive types in C# have an associated *.Parse/Convert.To* method that serve the same purpose as
Boolean.Parse()/Convert.ToBoolean()
.Convert.ToBoolean(string)
actually callsbool.Parse()
anyway, so for non-nullstring
s, there's no functional difference. (For nullstring
s,Convert.ToBoolean()
returnsfalse
, whereasbool.Parse()
throws anArgumentNullException
.)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 abool
from many other built-in types, whereasParse()
is forstring
s only.In terms of type.Parse() methods you should look out for, all the built-in numeric types have
Parse()
as well asTryParse()
methods.DateTime
has those, as well as the additionalParseExact()
/TryParseExact()
methods, which allow you specify an expected format for the date.