Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do bool.TrueString and bool.FalseString exist?

I was reading the MSDN article of the boolean structure, when I saw that a boolean has two fields: TrueString and FalseString. These respectively return "True" and "False".

After some searching, the only example I could find is in this dotnetperls article. The article states:

Programs often need these strings. TrueString and FalseString are a useful pair of readonly members. They represent truth values in string format. They provide indirection and abstraction over directly using string literals.

So appearantly it's useful for some situations. But the same article fails to provide a realistic example (IMHO anyway).

Some further reading also brought this to my attention: TrueString and FalseString are public static readonly fields. And this dornetperls article states:

The language specification recommends using public static readonly fields ... when the field is subject to change in the future.

Now this I can somewhat understand. If the .NET developers ever decide to change "True" and "False" to respectively "OkeyDokey" and "Negatory", it's smart to use TrueString and or FalseString.

But that still leaves me with the question: in what kind of scenario do you want to compare a string with the string literal of a boolean? Because appearantly: "Programs often need" them.

like image 657
Jordy Avatar asked Jul 03 '13 12:07

Jordy


People also ask

What is bool TrueString?

The TrueString property defines the string representation of a true Boolean value in formatting and parsing operations.

What is System Boolean?

NET System. Boolean structure type that represents a Boolean value, which can be either true or false . To perform logical operations with values of the bool type, use Boolean logical operators. The bool type is the result type of comparison and equality operators.


1 Answers

If the program stores data in a human readable file or database, it may need to store values as strings. When you read the data back in, if you know the data was written by your application and uses a standard string representation, you can compare x == bool.TrueString faster than you can bool.TryParse(x ...). You could also validate the data by making sure all values x == bool.TrueString || x == bool.FalseString

If the data was typed by humans, or a different system, TryParse is a better option, as it accepts more values as true and differentiates between a definite false and an invalid input. (MSDN Boolean TryParse)

like image 185
Denise Skidmore Avatar answered Oct 20 '22 13:10

Denise Skidmore