Confusing If Statement?

前端 未结 13 933
-上瘾入骨i
-上瘾入骨i 2020-12-20 13:03

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

if (IsSuccessed == true)
{
   //
}

I know that there is no need to write \"== true\"

13条回答
  •  难免孤独
    2020-12-20 13:28

    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.

提交回复
热议问题