Alexandre
Alexandre

Reputation: 13318

Expression is always true in C#

A 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 result in Console.WriteLine(result) is always true. Why?

Upvotes: 6

Views: 1301

Answers (3)

Eduard
Eduard

Reputation: 176

Because if(true && false) (thats what you get, when you resolve the parsing) will never enter the if body. Thats what you are parsing in the first example.

Upvotes: 2

manojlds
manojlds

Reputation: 301387

What Reharper is telling you is that, if you are doing

Console.WriteLine(result);

you might as well do

Console.WriteLine(true);

That is, anywhere you use result within the if, you can as well use true, as, if result were false, the you would not have reached the body of the if.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502816

It's due to the && result part - you'll only ever get into the body of the statement if result is true. How do you anticipate any way of getting in there with result being false?

Upvotes: 22

Related Questions