if(expression) should be boolean in C#


The expression in an if statement must be enclosed in parentheses. Additionally, the expression must be a Boolean expression. In some other languages (notably C and C++), we can write an integer expression, and the compiler will silently convert the integer value to true (non-zero) or false (0)  C# does not support this behavior, and the compiler reports an error if we write such an expression. If we accidentally specify the assignment operator, =, instead of the equality test operator, ==, in an if statement, the C# compiler recognizes your mistake and refuses to compile our code. For example:

int seconds;  
...  
if (seconds = 59)  // compile-time error  
...  
if (seconds == 59) // ok

Accidental assignments were another common source of bugs in C and C++ programs, which would silently convert the value assigned (59) to a Boolean expression (with anything nonzero considered to be true), with the result that the code following the if statement would be performed every time.

Incidentally, we can use a Boolean variable as the expression for an if statement, although it must still be enclosed in parentheses, as shown in this example:

bool inWord;  
...  
if (inWord == true) // ok, but not commonly used  
...  
if (inWord)         // more common and considered better style

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System