Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusing If Statement?

I always use If statement (In C#) as (1. Alternative);

if (IsSuccessed == true)
{
   //
}

I know that there is no need to write "== true" as (2. Alternative));

if (IsSuccessed)
{
   //
}

But, I use it because it is more readable and cause no performance issue. Of course, this is my choice and I know many software developers prefer first alternative. What is the best usage, and Why?

like image 315
NetSide Avatar asked Mar 09 '10 08:03

NetSide


1 Answers

I don't like the first option. Not only is it redundant, but a simple typo will introduce a bug.

Consider this

bool b = false;

if (b = true) {
   Console.WriteLine("true");
}

Obviously the code will output "true" but that was probably not the intention of the programmer.

Fortunately tools like Resharper warns against this, but it compiles with the default settings (*).

Using the bool directly will remove the issue entirely.

(*) To be fair, VS also warns against this and if you turn on Warnings as errors it won't even compile.

like image 75
Brian Rasmussen Avatar answered Oct 17 '22 05:10

Brian Rasmussen