SoFunction
Updated on 2025-03-08

Overview of the use of if statements in C#

There are many things worth learning about C# language. Here we mainly introduce the use of if statements in C#. If you want to choose to execute two different code blocks based on the result of a Boolean expression, you can use if statements in C#.
Understand the syntax of if statements

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

Copy the codeThe code is as follows:

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

If the booleanExpression evaluates to true, run statement-1; otherwise, run statement-2. The else keyword and subsequent statement-2 are optional. If there is no else clause, then nothing will happen if booleanExpression is false.

For example, the following if statement is used to increment the second hand of a stopwatch (minutes are temporarily ignored). If the value of seconds is 59, reset to 0; otherwise, use operator++ to increment:

Copy the codeThe code is as follows:

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

Use only boolean expressions!

C# expressions in use if statements must be placed in a pair of parentheses. In addition, the expression must be a boolean expression. In other languages ​​(especially C and C++), an integer expression can also be used, and the compiler can automatically convert integer values ​​to true (non-zero values) or false (zero values). 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 can also recognize your error. For example:

Copy the codeThe code is as follows:

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

Inadvertently writing assignment expressions is another reason why C and C++ programs are prone to bugs. In C and C++, the assigned value (59) is quietly converted into a Boolean value (any non-zero value will be considered true), resulting in the code after C# using the if statement is necessary to execute each time.

Finally, a Boolean variable can be used as an expression, as shown in the following example:

Copy the codeThe code is as follows:

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