In this article, we are going to talk about condition statements in C#. We will learn how to write simple condition statements, nested condition statements, and multiple condition statements.

For the complete navigation of this series check out: C# Back to Basics.

If you want to download the source code for our examples, you can do that from here Conditions in C# Source Code.

Let’s begin.

Basic Condition Statements

If we want to execute some expression but only if some condition is met, then we need to use conditional statements. To create such a statement we need to use if and else keywords.

We can create a conditional statement like this:

The condition is a logical expression which can result in true or false. If it is true then the <expression1> will be executed, otherwise, <expression2> will be executed. After every expression, we need to place the ; sign.

We can execute more expressions if the condition is true or false:

Example 1: Create an application which determines the greater number of two integer inputs:

Example 1 Conditions in C#

We don’t have to use only if and else keywords in conditional statements, we can add another condition by adding else if block part:

Example 2: Create an application which takes any string and the font color (r for red, g for green, o for other) as inputs. Then it needs to print out that string with the selected color:

Else if example Conditions in C#

Nested Conditional Statements

In C#, we can write a conditional statement inside a conditional statement if that’s one of the requirements of our project. So, the base syntax looks like this:

Even though we can create nested conditional statements, we do not recommend them that much, because it would lead to low readability.

Example 3: Create an application in which the user enters a number between 1 and 100. If the number is lower then 50, our application will output multiplication by 5. But if a number is greater then 50 then for even number application will output multiplication by 2 and for an odd number application will output multiplication by 3:

Nested Conditions in C#

Switch-Case Statements

In a situation where we need more than one or two conditions to execute some expression, using multiple branching could be an advantage. To use multiple branching in C#, we need to use switch and case keywords:

Example 4: Create an application which accepts month number as an input and prints out the number of days in that month:

Multiple Conditions in C#


Well done.

We this knowledge, we can create conditional structures in our code and make decisions based on whether the conditions are true or false.

If you have enjoyed reading this article and if you would like to receive the notifications about the freshly published .NET Core content we encourage you to subscribe to our blog.