The if statement in C USES an overview

  • 2020-06-15 10:07:42
  • OfStack

There is much to learn about the C# language, and here we focus on C# using if statements. C# USES the if statement if you want to execute two different blocks of code based on the result of one Boolean expression.
Understand the syntax of the if statement

The syntax for the if statement is as follows (if and else are the keywords) :


if ( booleanExpression )  
statement-1;  
else  
statement-2; 

If booleanExpression evaluates to true, run statement-1; Otherwise, run statement-2. The else keyword and subsequent ES23en-2 are optional. Without the else clause, nothing would happen under the premise that booleanExpression is false.

For example, the following if statement is used to increment the second hand of a stopwatch (ignore minutes for now). If the value of seconds is 59, reset to 0; Otherwise, use the operator ++ to increment:


int seconds;  
...  
if (seconds == 59)  
seconds = 0;  
else  
seconds++; 

Use only Boolean expressions!

Expressions in C# using if statements must be enclosed in 1 pair of parentheses. In addition, the expression must be a Boolean expression. In other languages (notably C and C++), an integer expression can also be used and the compiler can automatically convert integer values to true(non-zero) or false(zero). C# does not allow this. If you write such an expression, the compiler will report an error.

If you accidentally write an assignment expression in an if statement instead of performing an equality test, the C# compiler will also recognize your error. Such as:


int seconds;  
...  
if (seconds = 59) //  Compile time error   
...  
if (seconds == 59) //  correct  

Inadvertantly writing assignment expressions is another reason why C and C++ programs are prone to bug. In C and C++, the assigned value (59) is stealthily converted to a Boolean value (any non-zero value is treated as true), resulting in the code following the C# if statement being executed each time.

Finally, you can use a Boolean variable as an expression, as shown in the following example:


bool inWord;  
...  
if (inWord == true) //  Yes, but not very often   
...  
if (inWord) //  better   


Related articles: