Expression is always true in C #

Simple C # Code

bool result; if (bool.TryParse("false", out result) && result) { Console.WriteLine(result); } 

and

  bool result; if (bool.TryParse("tRue", out result) && result) { Console.WriteLine(result); } 

Resharper says that the result of Console.WriteLine(result) always true . Why?

+6
source share
3 answers

This is because of the && result part - you will only ever get into the body of the operator if result true. How do you expect any way to get result false ?

+22
source

What Reharper tells you that if you do

 Console.WriteLine(result); 

you can also do

 Console.WriteLine(true); 

That is, wherever you use the result in if, you can also use true, because if result were false, you would not have reached the if body.

+4
source

Because if(true && false) (this is what you get when you resolve the parsing) will never go into the body of the if. This is what you parse in the first example.

+2
source

Source: https://habr.com/ru/post/926691/


All Articles