Click to share! ⬇️

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.

bool condition = true;

if (condition)
{
    Console.WriteLine("condition is true.");
}
else
{
    Console.WriteLine("condition is false.");
}

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

if (age <= 2)
    StayHome();

else if (age < 18)
    GoToSchool();

else
{
    GoToWork();
}

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.

if (currentprice <= 9.99 )
{
    if (regularprice == 15.99)
    {
        Console.WriteLine("The item is on sale.");
    }
}

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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stocks
{
    public class StockStatistics
    {
        public StockStatistics()
        {
            HighestStock = 0;
            LowestStock = float.MaxValue;
        }

        public string StockValuation
        {
            get
            {
                string result;
                if (AverageStock >= 200)
                {
                    result = "Very Expensive";
                }
                else if (AverageStock >= 150)
                {
                    result = "Expensive";
                }
                else if (AverageStock >= 100)
                {
                    result = "Average";
                }
                else if (AverageStock >= 50)
                {
                    result = "Good Value";
                }
                else
                {
                    result = "Very Good Value";
                }
                return result;
            }
        }

        public float AverageStock;
        public float HighestStock;
        public float LowestStock;
    }
}

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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stocks
{
    class Program
    {
        static void Main(string[] args)
        {
            StockPortfolio portfolio = new StockPortfolio();

            portfolio.PortfolioNameChanged += OnPortfolioNameChanged;

            portfolio.Name = "'Warren Buffet Portfolio'";
            portfolio.Name = "'Bootleg Capital'";

            portfolio.AddStock(55.81f);
            portfolio.AddStock(74.52f);
            portfolio.AddStock(152.11f);
            portfolio.AddStock(199.85f);
            portfolio.AddStock(225.28f);

            StockStatistics stats = portfolio.ComputeStatistics();
            Console.WriteLine("The Current Name Is: " + portfolio.Name + "n");
            CustomWriteLine("The Average Stock Price Is: ", stats.AverageStock);
            CustomWriteLine("The Highest Stock Price Is: ", stats.HighestStock);
            CustomWriteLine("The Lowest Stock Price Is: ", stats.LowestStock);
            CustomWriteLine("Overall Valuation: ", stats.StockValuation);
        }

        static void OnPortfolioNameChanged(object sender, PortfolioNameChangedEventArgs args)
        {
            Console.WriteLine($"Portfolio name changed from {args.oldName} to {args.newName}! n");
        }

        static void CustomWriteLine(string description, float result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }

        static void CustomWriteLine(string description, string result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }
    }
}

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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stocks
{
    public class StockStatistics
    {
        public StockStatistics()
        {
            HighestStock = 0;
            LowestStock = float.MaxValue;
        }

        public string StockValuation
        {
            get
            {
                string result;
                if (AverageStock >= 200)
                {
                    result = "Very Expensive";
                }
                else if (AverageStock >= 150)
                {
                    result = "Expensive";
                }
                else if (AverageStock >= 100)
                {
                    result = "Average";
                }
                else if (AverageStock >= 50)
                {
                    result = "Good Value";
                }
                else
                {
                    result = "Very Good Value";
                }
                return result;
            }
        }

        public string Recommendation
        {
            get
            {
                string result;
                switch (StockValuation)
                {
                    case "Very Expensive":
                        result = "Take profits.";
                        break;
                    case "Expensive":
                        result = "Sell some, hold some.";
                        break;
                    case "Average":
                        result = "Continue to hold.";
                        break;
                    case "Good Value":
                        result = "Consider buying.";
                        break;
                    default:
                        result = "Buy.";
                        break;
                }
                return result;
            }
        }

        public float AverageStock;
        public float HighestStock;
        public float LowestStock;
    }
}

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stocks
{
    class Program
    {
        static void Main(string[] args)
        {
            StockPortfolio portfolio = new StockPortfolio();

            portfolio.PortfolioNameChanged += OnPortfolioNameChanged;

            portfolio.Name = "'Warren Buffet Portfolio'";
            portfolio.Name = "'Bootleg Capital'";

            portfolio.AddStock(55.81f);
            portfolio.AddStock(74.52f);
            portfolio.AddStock(152.11f);
            portfolio.AddStock(199.85f);
            portfolio.AddStock(225.28f);

            StockStatistics stats = portfolio.ComputeStatistics();
            Console.WriteLine("The Current Name Is: " + portfolio.Name + "n");
            CustomWriteLine("The Average Stock Price Is: ", stats.AverageStock);
            CustomWriteLine("The Highest Stock Price Is: ", stats.HighestStock);
            CustomWriteLine("The Lowest Stock Price Is: ", stats.LowestStock);
            CustomWriteLine("Overall Valuation: ", stats.StockValuation);
            CustomWriteLine("Current Recommendation: ", stats.Recommendation);
        }

        static void OnPortfolioNameChanged(object sender, PortfolioNameChangedEventArgs args)
        {
            Console.WriteLine($"Portfolio name changed from {args.oldName} to {args.newName}! n");
        }

        static void CustomWriteLine(string description, float result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }

        static void CustomWriteLine(string description, string result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }
    }
}

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

for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}
0
1
2
3
4
5
6
7
8
9

C# while

int n = 0;
while (n < 7)
{
    Console.WriteLine(n);
    n++;
}
0
1
2
3
4
5
6

C# do while

int n = 0;
do 
{
    Console.WriteLine(n);
    n++;
} while (n < 3);
0
1
2

C# foreach

var numbers = new List<int> { 0, 5, 10, 15, 20, 25, 30, 35 };
int count = 0;
foreach (int element in numbers)
{
    count++;
    Console.WriteLine($"Element #{count}: {element}");
}
Console.WriteLine($"Number of elements: {count}");</int>
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.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stocks
{
    class Program
    {
        static void Main(string[] args)
        {
            StockPortfolio portfolio = new StockPortfolio();

            portfolio.PortfolioNameChanged += OnPortfolioNameChanged;

            portfolio.Name = "'Warren Buffet Portfolio'";
            portfolio.Name = "'Bootleg Capital'";

            portfolio.AddStock(55.81f);
            portfolio.AddStock(74.52f);
            portfolio.AddStock(152.11f);
            portfolio.AddStock(199.85f);
            portfolio.AddStock(225.28f);
            portfolio.ListStocks(Console.Out);

            StockStatistics stats = portfolio.ComputeStatistics();
            Console.WriteLine("The Current Name Is: " + portfolio.Name + "n");
            CustomWriteLine("The Average Stock Price Is: ", stats.AverageStock);
            CustomWriteLine("The Highest Stock Price Is: ", stats.HighestStock);
            CustomWriteLine("The Lowest Stock Price Is: ", stats.LowestStock);
            CustomWriteLine("Overall Valuation: ", stats.StockValuation);
            CustomWriteLine("Current Recommendation: ", stats.Recommendation);
        }

        static void OnPortfolioNameChanged(object sender, PortfolioNameChangedEventArgs args)
        {
            Console.WriteLine($"Portfolio name changed from {args.oldName} to {args.newName}! n");
        }

        static void CustomWriteLine(string description, float result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }

        static void CustomWriteLine(string description, string result)
        {
            Console.WriteLine($"{description}: {result:C} n", description, result);
        }
    }
}

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.

using System;
using System.Collections.Generic;
using System.IO;

namespace Stocks
{
    public class StockPortfolio
    {
        public StockPortfolio()
        {
            _name = "'Starting Name'";
            stocks = new List<float>();
        }

        public StockStatistics ComputeStatistics()
        {
            StockStatistics stats = new StockStatistics();

            float sum = 0;
            foreach (float stock in stocks)
            {
                stats.HighestStock = Math.Max(stock, stats.HighestStock);
                stats.LowestStock = Math.Min(stock, stats.LowestStock);
                sum += stock;
            }

            stats.AverageStock = sum / stocks.Count;
            return stats;
        }

        public void ListStocks(TextWriter destination)
        {
            Console.WriteLine("The list of stock prices is");
            for (int i = 0; i < stocks.Count; i++)
            {
                destination.WriteLine(stocks[i]);
            }
            Console.WriteLine("n");
        }

        public void AddStock(float stock)
        {
            stocks.Add(stock);
        }

        public string Name
        {
            get { return _name; }
            set
            {
                if (!String.IsNullOrEmpty(value))
                {
                    if (_name != value)
                    {
                        PortfolioNameChangedEventArgs args = new PortfolioNameChangedEventArgs();
                        args.oldName = _name;
                        args.newName = value;
                        PortfolioNameChanged(this, args);
                    }
                    _name = value;
                }
            }
        }

        public event PortfolioNameChangedDelegate PortfolioNameChanged;

        private string _name;
        private List<float> stocks;
    }
}</float></float>

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.

for (int i = 1; i <= 50; i++)
{
    if (i == 7)
    {
        break;
    }
    Console.WriteLine(i);
}
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.

for (int i = 1; i <= 5; i++)
{
    if (i < 4)
    {
        continue;
    }
    Console.WriteLine(i);
}
4
5

C# goto

Shifts control directly to a labeled point in the program.

int[] nums = new int[] { 1, 2, 3, 4, 5 };
foreach (int num in nums)
{
    if (num == 3)
    {
        goto target;
    }
    Console.WriteLine(num);
}
target:
Console.WriteLine("Stopping at 3!");
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.

static int One()
{
    // This method returns an integer.
    return 100;
}

static string Two()
{
    // This method returns a string.
    return "Hi There!";
}

static int Three(int num1, int num2)
{
    // This method returns an integer based on an expression.
    return (num1 * 10) + num2;
}

static void Four()
{
    // This method uses a return statement with no expression (void).
    Console.WriteLine("Four executed");
    return;
}

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.

Click to share! ⬇️