Application Flow Control and Control Structures in C#

Flow Control via conditional statements allow different sections of code to be ran depending on a condition being met or not met.

1,124 words, estimated reading time 4 minutes.
Introduction to Programming with C#

This article is part of a series of articles. Please use the links below to navigate between the articles.

  1. Learn to Program in C# - Full Introduction to Programming Course
  2. Introdution to Programming - C# Programming Fundamentals
  3. Guide to C# Data Types, Variables and Object Casting
  4. C# Operators: Arithmetic, Comparison, Logical and more
  5. Application Flow Control and Control Structures in C#
  6. Introduction to Object Oriented Programming for Beginners
  7. Introduction to C# Object-Oriented Programming Part 2
  8. C# Collection Types (Array,List,Dictionary,HashTable and More)
  9. Error and Exception Handling in C#
  10. Events, Delegates and Extension Methods
  11. Complete Guide to File Handling in C# - Reading and Writing Files
  12. Introduction to XML and XmlDocument with C#
  13. What is LINQ? The .NET Language Integrated Query
  14. Introduction to Asynchronous Programming in C#
  15. Working with Databases using Entity Framework
  16. All About Reflection in C# To Read Metadata and Find Assemblies
  17. Debugging and Testing in C#
  18. Introduction to ASP.Net MVC Web Applications and C#
  19. Windows Application Development Using .Net and Windows Forms
  20. Assemblies and the Global Assembly Cache in C#
  21. Working with Resources Files, Culture & Regions in .Net
  22. The Ultimate Guide to Regular Expressions: Everything You Need to Know
Application Flow Control and Control Structures in C#

Flow Control via conditional statements allow different sections of code to be ran depending on a condition being met or not met.

Flow Control Conditional Statements in C#

Conditions can be used to validate user input and display certain data depending on the date, day of the week, or any of thousands of conditions.

If...Else Flow Control

The most commonly used conditional statement is the If...Else block, a statement is evaluated as true or false and a different code section is executed depending on the result.

In this sample, the statement checks if the condition is true. If it is, it executes the first block of code. If the condition is false, then it executes the second.

Conditions in the if statement must ALWAYS be evaluated as TRUE or FALSE.

C#
int x = 5;

if (x >= 3)
{
  Console.WriteLine("X is greater than or equal to 3.");
}
else
{
  Console.WriteLine("X is less than 3.");
}

Have a play by changing the value of X and seeing which code block is executed.

If you only have ONE statement to be executed, like in our example, you can omit the braces, but if you have more than one statement, you will need the braces. This can make the code easier to read, but some consider it bad form.

C#
int x = 5;

if (x >= 3)
  Console.WriteLine("X is greater than or equal to 3.");
else
  Console.WriteLine("X is less than 3.");

You don't need to have an else statement. If all you want is to output something on Monday, for example:

C#
if (dayOfWeek == Monday)
  Console.WriteLine("Today is Monday");

This will write out "Today is Monday" only if the dayOfWeek is Monday; otherwise, the code will be skipped over.

Nested If Statements and Flow Control

If you have multiple scenarios, you can nest if... else statements:

C#
if (dayOfWeek == Monday)
  Console.WriteLine("Today is Monday");
else if (dayOfWeek == Tuesday)
  Console.WriteLine("Today is Tuesday");
else if (dayOfWeek == Wednesday)
  Console.WriteLine("Today is Wednesday");
else if (dayOfWeek == Thursday)
  Console.WriteLine("Today is Thursday");
else if (dayOfWeek == Friday)
  Console.WriteLine("Today is Friday");

This can get complicated for many conditions, so using a switch statement is much easier and more efficient.

Flow chart planning on whiteboard
Flow Control and Control Structures in C#

Switch Statement

In the previous example with the multiple daysOfWeek, the program executed four if statements by the time Friday was tested, which is inefficient. The code is also difficult to read and understand, so a better method would be using a switch case statement.

The above example can be simplified to this:

C#
switch(dayOfWeek)
{
  case "Monday": 
    Console.WriteLine("Today is Monday");
    break;
  case "Tuesday": 
    Console.WriteLine("Today is Tuesday");
    break;
  case "Wednesday": 
    Console.WriteLine("Today is Wednesday");
    break;
  case "Thursday": 
    Console.WriteLine("Today is Thursday");
    break;
  case "Friday": 
    Console.WriteLine("Today is Friday");
    break;
}

As you can see, this is much easier to read, and only one conditional statement gets executed, so the code is more efficient and faster to execute. Each section of code to execute ends with a break keyword. This tells the compiler that the case has ended. Unlike some languages, such as PHP, you cannot "fall through" case blocks if the code exists. You can only fall through when one case directly follows another case statement:

C#
case "Saturday":
  Console.WriteLine("Today is a Weekend"); // This will ERROR!
case "Sunday":
  Console.WriteLine("Today is a Weekend");
  break;
C#
case "Saturday":
case "Sunday":
  Console.WriteLine("Today is a Weekend"); // This is OK!
  break;

Another useful part of the Switch...Case block is that of a default action. The default will be executed if none of the specified cases is met.

C#
switch(dayOfWeek)
{
  case "Monday": 
    Console.WriteLine("Today is Monday");
    break;
  case "Tuesday": 
    Console.WriteLine("Today is Tuesday");
    break;
  case "Wednesday": 
    Console.WriteLine("Today is Wednesday");
    break;
  case "Thursday": 
    Console.WriteLine("Today is Thursday");
    break;
  case "Friday": 
    Console.WriteLine("Today is Friday");
    break;
  default:
    Console.WriteLine("This the weekend!!!");
    break;
}

The default must always be the last statement.

C# allows the use of other keywords and breaks to control the flow of the Switch statement. You can use goto, return and throw.

Goto

The use of Goto does not fall within the structured programming methodology and should be avoided at all costs.

Return

The return keyword is used to return a value to the calling function.

Throw

The throw raises an exception, which your Try will capture... Catch block. This will be covered in much more detail in the section about Exception Handling.

Looping and Iteration in C#

When programming, it is often necessary to repeat a task many times. This is a process known as iteration or looping. C# has several methods for looping: Do, While, For, and Foreach. In this article, we look at each and how you use them.

The type of iterative loop is governed by how it should perform and what data types are involved. Some loops check the exit condition before they exit the loop, while others guarantee at least one pass.

The While Loop

The simplest loop is the while loop. This loop executes a code block while the condition is true.

C#
int i = 1;
while (i <= 10)
{
  Console.WriteLine($"Loop {i}");
  i++;
}

This will output:

Loop: 1
Loop: 2
Loop: 3
Loop: 4
Loop: 5
Loop: 6
Loop: 7
Loop: 8
Loop: 9
Loop: 10

There is a danger, however, that you will get caught in an infinite loop.

An infinite loop occurs when the exit condition is never met, an example of which would be if you forgot to increment i within the loop. The exit condition will always be less than 10, so the loop will never exit.

A while loop will check the condition before entering the loop, and if the condition is met the first time, there will be no loop.

C#
int i = 12;
while (i <= 10)
{
  Console.WriteLine($"Loop {i}");
  i++;
}

The Do... While Loop

The do-while loop is similar to the while loop, except it does not check the condition until the end of the first iteration. You are guaranteed to have a minimum of one iteration every time.

C#
int i = 1;
do
{
  Console.WriteLine($"Loop {i}");
  i++;
} while (i <= 10);

Again, you must increment the loop counter to avoid being caught in an infinite loop.

The For Loop

The for loop is one of the most common types of loops. It will loop from a starting count to an ending count and then stop. For example, you can loop through numbers 1 to 10. The basic format for a statement is:

C#
for (start value; end condition; increment counter)
{
  // Code to repeat
}

Looping from 1 to 10 as our first example will be coded as follows:

C#
for (int i = 1; i <= 10; i++)
{
  // Code to repeat
}

It doesn't look very easy, so we'll go through each aspect in turn.

  • int i = 1: Declares a variable called i and initiates the value to 1. This is the loop starting value.
  • i<=10: The program will loop as long as i <= 10. Once this condition is no longer met, the loop will exit.
  • i++: Increment the value of i by 1 for the next iteration.

You cannot change the value of i within the code to repeat, but you can access its value:

C#
for (int i = 1; i <= 10; i++)
{
  i = 67; // This line will ERROR!
  Console.WriteLine($"Loop {i}");
}

The ending condition does not have to be a fixed value; you can use a function that returns an int. For example, you can loop through all the values in an array (these will be covered later) using the count function to return the number of elements in the array. You can then use the value of i to access the array element.

C#
string[] daysOfWeek = new string[] {
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday"
};

for (int i = 0; i < daysOfWeek.Length; i++)
{
    Console.WriteLine($"Day of Week: {daysOfWeek[i]}");
}

Will output:

Day of Week: Monday
Day of Week: Tuesday
Day of Week: Wednesday
Day of Week: Thursday
Day of Week: Friday

Foreach

The for statement has many individual statements that implement the loop mechanism to iterate through the items of an array. It isn't intuitive and is prone to errors, such as forgetting that the array index starts from 0 and the array length starts from 1. A foreach statement is better in terms of readability and is less error-prone. However, there is a slight performance decrease compared with a for loop.

To iterate through the daysOfWeek array from the previous code, the for loop can be replaced with a foreach:

C#
foreach(string Day in daysOfWeek)
{
  Console.WriteLine($"Day: {Day}");
}

It is much easier to understand what is happening in this example. We declare a value Day of type string (must be the same as the array data type) and it automatically gets assigned the value of daysOfWeek. On the next iteration, we get the next array item, and so on, until the end of the array is reached.

You cannot assign to the value of Day in this example as it is read only, nor can you modify the daysOfWeek collection.

Loop Control

You can use two statements to control the loop from the inside. The first will skip processing the current iteration and continue onto the next. These keywords can be used for or foreach loop in a while.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 10; i++)
            {
                if (i == 5)
                    continue;

                Console.WriteLine(i);
            }
        }
    }
}

This will output:

1
2
3
4
6
7
8
9
10
Press any key to continue . . .

As you can see, once the continue statement is reached, no other code in that iteration will run; the loop counter gets incremented, and the loop continues.

The other control keyword is break, which is used to break out of the loop altogether.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i <= 10; i++)
            {
                if (i == 5)
                    break;

                Console.WriteLine(i);
            }
        }
    }
}

Will output:

1
2
3
4
Press any key to continue . . .

Recursion

Recursion is the process whereby a method calls itself until an exit condition is met. Very useful, but also very easy to shoot yourself in the foot over and over and over again.

Recursion is used where a method processes items and calls itself repeatedly to process further items it finds. An example would be a directory tree listing. It first scans the root of the C: drive and then calls itself for each directory found. If a subdirectory also contains directories, another call to itself is made.

Recursion is also used in mathematics, scientific programming, node programming, artificial intelligence, and database applications.

Recursion is a good way of reusing code and processing multiple levels of data. However, it is very easy for the system to run away. You also need to pass data to a method that can be memory intensive. It will also have an impact on performance.

The following code sample illustrates a recursive method for listing a directory structure.

C#
using System;
using System.Threading;
using System.Text;
using System.IO;

class Program
{
    static void Main()
    {
        StringBuilder dirList = new StringBuilder();

        dirList = directoryListing("c:/Inetpub", "");
        Console.WriteLine(dirList.ToString());
    }

    static StringBuilder directoryListing(string path, string indent)
    {
        StringBuilder result = new StringBuilder();
        DirectoryInfo di = new DirectoryInfo(path);
        DirectoryInfo[] directories = di.GetDirectories();

        foreach (DirectoryInfo dir in directories)
        {
            result.AppendLine(indent + dir.Name);

            // Call the method again on the directories found
            result.Append(directoryListing(dir.FullName, indent + "..").ToString());
        }
        return result;
    }
}

This routine will scan through the directory specified in the Main method, grab all the subdirectories within that directory, add them to the result, and then call itself on each subdirectory found. It will recurse until a folder has no subdirectories. It returns the result to the recursive method line until no more recursions are processed. The result is then handed back to the Main method call.

Each time the recursive method is called, you need to tell it where to start from, in this case, the folder to look in. In this example, I also use a parameter for the indent level. Each recursion adds two dots to the previous indent level to see the directory structure.

It is very easy for a recursive method to run away with itself; an invalid parameter or start point will cause the method to call itself repeatedly and never progress. In this case, you will eventually receive a StackOverflowException, which should be handled with a try-catch block on the first call of the method.

Summary and Conclusions

We have seen how to use conditional statements to perform different actions based on whether the condition evaluates to true or false. We also saw how a switch statement can be used where there are multiple if-else statements to improve readability and performance. We have seen the four iterative loops, while, do while, for and foreach, and how they can be used to repeat an action on certain types of data repeatedly. We then saw how recursion can repeat an action over a directory structure.

About the Author

Tim Trott is a senior software engineer with over 20 years of experience in designing, building, and maintaining software systems across a range of industries. Passionate about clean code, scalable architecture, and continuous learning, he specialises in creating robust solutions that solve real-world problems. He is currently based in Edinburgh, where he develops innovative software and collaborates with teams around the globe.

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

My website and its content are free to use without the clutter of adverts, popups, marketing messages or anything else like that. If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

New comments for this post are currently closed.