Why do bool.TrueString and bool.FalseString exist?

I read the MSDN article of the boolean structure when I saw that the boolean has two fields: TrueString and FalseString . They respectively return "True" and "False".

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

Programs often need these lines. TrueString and FalseString are a useful pair of read-only members. They represent truth values โ€‹โ€‹in a string format. They provide indirect and abstraction directly using string literals.

So maybe this is useful for some situations. But the same article does not provide a realistic example (IMHO).

Some additional reading also caught my attention: TrueString and FalseString are readonly public static fields. And this dornetperls article reads:

The language specification recommends using readonly public static fields ... when the field may be changed in the future.

Now I can understand a little. If .NET developers ever decide to change "True" and "False" respectively to "OkeyDokey" and "Negative", it is wise to use TrueString and FalseString.

But that still leaves me with the question: in which scenario do you want to compare a string with a boolean string literal? Because clearly: โ€œPrograms often needโ€ them.

+8
c # boolean string-literals
source share
2 answers

Simply put. Boolean is a structure. this boolean method produces the ToString () method, which is user-readable text for users. Therefore, if you write something like this.

bool b = false; b.ToString(); 

the output will be "False" insteed of 0. "False" is human readable and easily captured.

Also some where you can parse a text value into a boolean value. therefore, they can also be represented as Boolean values. eg. we use

 Boolean.TryParse("false" ,out mybool) 

a false value is set by the Tryparse method, as this detects that we can read values โ€‹โ€‹from string tools.

0
source share

If the program stores data in a humanoid file or database, you may need to save the values โ€‹โ€‹as strings. When you read the data again, if you know that the data was written by your application and uses the standard string representation, you can compare x == bool.TrueString faster than you can bool.TryParse(x ...) . You can also check the data by making sure that all values โ€‹โ€‹are x == bool.TrueString || x == bool.FalseString x == bool.TrueString || x == bool.FalseString

If the data was entered by people or another system, TryParse is the best option because it takes more values โ€‹โ€‹as true and distinguishes between certain false and invalid values. ( MSL Boolean TryParse )

0
source share

All Articles