In this article, the latest of our C## in Simple Terms series, we’re going to discuss how to control the flow of execution in a C## program. This means we will answer the question, “how does the code know what to do next?”

Our C## programs know what lines of code to execute next through the use of two sets of keywords: the selection statement keywords, and the loop keywords.

Code Blocks

In C#, a code block is a group of lines of code between curly braces {}.

{
    //Everything between { and } is part of this code block.
}

Both selection statement keywords and loops work with code blocks, though in different ways.

Selection Statement Keywords

These keywords cause “decision points” in C## programs, where the program may or may not execute a code block based on whether a condition or set of conditions is true.

In C#, this set of keywords consists of ifelseswitchcase, and break. Let’s take a closer look at each of these keywords.

If, Else, If Else

The most basic of the selection statement keywords are if and else. We use these keywords to evaluate boolean expressions and direct the program to execute specified lines of code if certain expressions are true.

if (expression) //If this expression evaluates to true...
{
    //...Execute this
}
else
{
    //Otherwise, execute this
}

We can also use an else if clause to add more conditions to our evaluation.

decimal money;
decimal orderTotal;

if (money > orderTotal)
{
    Console.WriteLine("Thanks for your purchase!");
}
else if (money == orderTotal)
{
    Console.WriteLine("Wow! Thanks for having exact change!");
}
else
{
    Console.WriteLine("Sorry, you don't have enough money.");
}

#c# in simple terms #c++

C# in Simple Terms - Code Blocks, Basic Statements, and Loops
1.10 GEEK