Decision Making with C#

It is time to put your critical thinking hat on today be

cause today we are going to go over decision making in C#. If you have been following along on my blog, you will know that I am currently covering the basics of the C# programming language as a way to kickstart my way back into blogging. This blog post is just one of many C# articles posted and to be posted on this blog.

Iteration Statements

The scenarios are endless for when you will need to repeat things in C# for one reason or another. Iteration statements will help you do just that. Below I will show you four types of iterations statements that you will see as a C# developer.

For

The first iteration statement is the for loop. It is used to repeat code a certain number of times with the condition checked at the beginning of the loop and each iteration after that.

for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}

In the above example, you see a for loop that will iterate 5 times. The int i = 0; is executed first but only once. The i < 5;  is the condition. It is evaluated to determine if the body of the for statement should be run. The i++;  is the increment which runs at the end of the body. The condition is then evaluated again. When the condition evaluates to false, the body is not run.

For-each

The foreach loop will loop over a collection of items as shown in the example below.

string[] People = new[] {"Joe", "John", "Mary"};

foreach (var person in People)
{
    Console.WriteLine(person);   
}

Above you see we have an array of strings called People with 3 names.  When the foreach loop runs all 3 names will be output to the console.

While

A while loop is very similar to a for loop. The difference being there is no initializer or incrementer in a while loop declaration. The incrementing variable must already exist before the while statement, and the incrementing must be done inside the loop to avoid an infinite loop.

int i = 0;

while (i < 5)
{
    Console.WriteLine(i);
    i++;
}

Above you see a while loop that outputs to the console the numbers 0 through 4. The variable i existed before the while statement and incremented inside the body of the loop.

Do-while

A do-while loop is the same as a while loop except the body of the loop is guaranteed to run at least once.

int i = 0;

do
{
    Console.WriteLine(i);
    i++;
} while (i > 2);

Conditionals

Now we are going to cover conditional statements. You use conditionals when you need your code to come to a fork in the road. You can then make a decision based on some logic.

If-else

The first conditional we are covering is the if-else statement. The way an if-else statement works is simple. Declare a condition and if that condition evaluates to true, then the body of the if statement is run. Otherwise, the body of the else statement runs.

if (1 < 5)
{
    Console.WriteLine("1 is less than 5");
}
else
{
    Console.WriteLine("1 is not less than 5");
}

In the above example, you see that the condition of the if statement is evaluated to true and therefore “1 is less than 5” is written to the console. If 1 had been greater than 5, then the condition would have evaluated to false causing the code in the else block to run.

You do not have to include the else statement after the if statement as shown above. You can leave it off so your code will do nothing when the condition is false.

If there is only one line of code inside the if or else blocks, then you do not have to include the surrounding brackets.

Conditional Operator

The conditional operator is a shorthand way of writing simple if-else statements which can help clean up your lines of code.

The first part of the conditional operator is the condition which is enclosed in parenthesis. Followed by a question mark followed by what to do if true, a colon, and what to do if false.

Below you see a comparison of setting a variable using an if-else and then again using the conditional. Which would you rather type?

int input = 1;
string myString;

// if-else
if (input > 0)
    myString = "positive";
else
    myString = "negative";

// Conditional operator.
    myString = (input > 0) ? "positive" : "negative";

Switch-case

Sometimes you may find yourself writing several if statements in a row. This is when a switch-case may be able to help you.

A switch case takes a variable and then decides which case to do based on the value of that variable. If there is no condition for the value of the variable coming in, then you can provide an optional default case.

int number = 2;
switch (number)
{
    case 1:
        Console.WriteLine(1);
        break;
    case 2:
        Console.WriteLine(2);
        break;
    default:
        Console.WriteLine("No cases matched");
        break;
 }

Above you see the number 2 come into the switch. It is then determined to run the second case which outputs the number 2 the console. If the value of the variable number had been 5 then the default case would have run.

Now that you know the basics of loops and logic in C#, you can make decisions in your code. If you feel like I have missed something or have any suggestions, please leave a comment below.

If you found this article helpful be sure to check out my C# Roadmap.