Confusing If Statement?

前端 未结 13 884
-上瘾入骨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:18

    The two expressions are equivalent in C#, but be aware than in other languages they are not.

    For example, in C++, the first option accepts only a boolean value with a value of true. Any other value on IsSuccessed will invalidate the condition.

    The second option accepts any value that is "truthy": values like 1, or any non-zero, are also considered valid for the if.

    So these conditions will validate:

    // Truthy validation (second option)
    if(1) {...} //validates
    if(2) {...} //validates
    

    While these others will not:

    // Equals to true validation (first option)
    if(1==true) {...} // does not validate
    if(2==true) {...} // does not validate
    

    Again, this doesn't apply to C#, since it only accepts booleans on ifs. But keep in mind that other languages accept more than just booleans there.

提交回复
热议问题