|

C# Control Statements

C Sharp Control Statements

Software needs a way to make decisions as it makes progress through the execution of code. This is where control flow comes into play. The program control flow is provided to us by use of control statements. These are the special keywords in the C# language that allow the programmer to set up things like branching, looping, and even entire jumps to new points in the program during execution. Let’s take a look at these keywords and constructs like if, switch, do while, for, foreach, while, break, return, and a few others.


The C# if Statement

By using an if statement in a program, a developer can make a decision based on a certain condition. Imagine coming to a fork in the road. Which way do you choose? In your head you will likely evaluate some conditions. If I go left, then I will arrive at the destination on time. If I go right, the scenery will be better. So you decide to go right like any rational person would. The if statement in C# allows us to do this type of thing in code. The if statement selects a branch for execution based on the value of a Boolean expression. That’s a fancy way of saying, if something is true, do this, otherwise do that. Here is an example in C# code.

Here is another example of the if statement which demonstrates that sometimes you do not have to include curly braces.

We can see in the snippet above that there are no curly braces used to surround the call to StayHome(). In most cases however, it is considered a good coding style to use curly braces because they make the code easier to maintain as well as more readable. You can only omit the curly braces when there is just one line of code to evaluate. The curly braces are always required if you need to execute more than one statement. So when setting up a block of code, or multiple lines of code, surround that with the curly braces. If you do not, then only the first line after the if statement will be executed. If the first expression inside of an if statement returns false, let’s say that age is a 17, then StayHome() does not get called. The program will jump to the next if statement to evaluate that one. If that one is true, you GoToSchool(). If both the first and second if statements are false, you GoToWork().


Nesting if statements

You can nest if statements if you like. In the code below, the program will only write out that “The item is on sale” if both if conditions evaluate to true. You should take care when nesting several if statements together since the code can become hard to read.


C# Ternary Operator

A really convenient control statement you can use is the ternary operator, called the conditional operator in C#. It has three parts.

csharp ternary conditional operator
The first part is an expression that needs to return true or false. If the expression returns true, we’ll return the value in part2 that is on the left-hand side of the colon. Otherwise we’ll return the value in part3 on the right-hand side of the colon. This conditional operator is great for a quick conditional check to assign one of two different values to a variable. That is how you most often see it being used. The same exact logic can be done with an if statement, but with a ternary operator there’s fewer characters to type. It’s best to use this for simple logic checks. If you put some complicated logic in the realm of a conditional operator, things can get difficult to read.


Branching

Let’s try some branching in our project. What we want to do is add a way for the StockStatistics class to determine the overall valuation of the stock portfolio. Here is how we’ll set that up.

What we are doing here is to look at the average stock price in the portfolio to get an idea if things are currently a good value, or perhaps expensive to very expensive. We can add this to the output of our program by modifying a couple of things in Program.cs. Here, we want to add this additional output that gives us information about the Overall Valuation. For that to happen, we also need to add an overloaded method for CustomWriteLine() which takes two string parameters.

Now when we run the program, we get this additional output as we see here.
start without debugging output


C# Switch Statements

In C# we also have a switch statement. It can be used to branch the execution of a program to a set of statements that are inside of a case label, which is created with the keyword case. The C# switch statement does this by matching the value inside the switch against the values that you specify in each case label.

  • Restricted to integers, characters, strings, and enums
  • Case labels are constants
  • Default label is optional

With this knowledge, we want to set up a recommendation function to the StockStatistic class. We’ll use a switch statement to help us out with that. What this switch statement will do is look at the StockValuation property that we just created. It is a string value. For each case we look at the string value to see if it is a match, and if so, provide the associated recommendation.

In the Program.cs file, we’ll need to add the highlighted line of code here to add this additional output in the program.

We can see the result of this new output here.
c sharp switch example output
The switch statement is not great for evaluating ranges, but is sometimes useful for replacing if / else / if statements.


Iterating in C#

Iterating is also known as looping. Looping is when you need or want to execute a piece of code many times. To iterate in C#, you can use either the for, while, do while, or foreach constructs.


C# for

0
1
2
3
4
5
6
7
8
9

C# while

0
1
2
3
4
5
6

C# do while

0
1
2

C# foreach

Element #1: 0
Element #2: 5
Element #3: 10
Element #4: 15
Element #5: 20
Element #6: 25
Element #7: 30
Element #8: 35
Number of elements: 8

We can practice some iterating constructs in our example program as well. Lets add a feature that lists out all of the stock prices that have been added to the program. First, in Program.cs we’ll add this highlighted code.

Then, in StockPortolio.cs we’ll need to implement that method. It makes use of the TextWriter type in .net, and loops over the collection of stocks in the program. As it loops over each one, it will write it out to the console.

And now we see the result of our iteration in action!
c sharp iterating with for loop


Jumping in C#

In C# you can jump to a specific point in the program by using one of the following keywords.

  • break
  • continue
  • goto
  • return

We saw that break is used in combination with the case label inside of a switch statement. It can also be used inside of a while, do while, for, or a foreach loop to break out and stop the looping.


C# break

Stops the closest enclosing loop or switch statement in which it appears.

1
2
3
4
5
6

C# continue

Passes control to the next iteration of the enclosing while, do, for, or foreach loop in which it appears.

4
5

C# goto

Shifts control directly to a labeled point in the program.

1
2
Stopping at 3!

C# return

Halts execution of the method where it appears and sends control back to the calling code. Often returns a value but does not have to.


C# Control Statements Summary

In this tutorial, we covered the various types of flow control statements available to us in the C# programming language. Control statements are roughly categorized into those that perform Branching, those for Looping, and those for Jumping. Branching statements include if, else if, the conditional operator, and the switch statement. When we need to iterate over things, or perform looping, we look to the for, while, do while, and foreach statements. Lastly, we looked briefly at Jumping constructs like break, continue, goto, and return.