Understanding Selection Statement
Learn how to use selection statements like if and switch in C# for branching code execution based on conditions, providing practical examples for both patterns.
We'll cover the following
Every application needs to be able to select from choices and branch along different code paths. The two selection statements in C# are if
and switch
. We can use it for all our code, but the switch
can simplify it in common scenarios, such as when a single variable with multiple values requires different processing.
Branching with the if
statement
The if
statement determines which branch to follow by evaluating a boolean expression. If the expression is true, then the block executes. The else
block is optional and executes if the if
expression is false.
Get hands-on with 1400+ tech skills courses.