SpackJarrow SpackJarrow - 9 months ago 61
ASP.NET (C#) Question

Why do Boolean.TryParse()] and Convert.ToBoolean() evaluate a string differently?

Why do Boolean.TryParse() and Convert.ToBoolean() evaluate a string differently?

I understand how they end up evaluating differently:

  1. Boolean.TryParse() will match (case insensitive) 'true' and 'false'.

  2. Convert.ToBoolean() will match to a whole range of values (example demonstrated in Microsoft doco linked above) which I would consider more natural.

Its the reasoning behind the difference I dont understand.

There are a couple of discussions touching on this subject which don't seem to address this particular question.

Answer Source

It's in the method/class names.

Convert -> you already have some value, you convert it to another type. e.g. you have value 1 which can be converted to true.

Parse -> you have the value as a string and you parse it.