C# Conditions

Conditions are used to execute part of a code only if some predefined requirements (conditions) are fulfilled. For example, a condition could be that a date must be after January 1, 2012 or that a variable is greater than 7.

Contents

C# If Condition

The first type of condition we will look at is if-condition, which has the following syntax:

1 if (condition) 
2 {
3    statement
4 }

Again, the syntax is very close to ordinary English: If a condition is met, then execute something. Let’s look at a simple example:

 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         int i = 2;
 6 
 7         if (i > 1) {
 8             Console.WriteLine("variable i is greater than 1");
 9         }
10 
11         Console.ReadLine();
12     }
13 }	 

C# If-Else Condition

The next type of condition will want to look at is else , which may be presented in the following form:

1 if (condition) 
2 {
3 	statement
4 }
5 else 
6 {
7 	statement
8 }

Again, the syntax is very close to ordinary English: if a condition is met execute something or else execute something else.

In previous chapter, you learned how to find the number of a month. In the following example, we will use the month number in an if-else condition to find out what season it is:

 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         var today = DateTime.Now;
 6         if (today.Month == 3)
 7         {
 8             Console.WriteLine("Now it's spring!");
 9         }
10         else
11         {
12             Console.WriteLine("I do not know what season it is!");
13         }
14 
15         Console.ReadLine();
16     }
17 }

As you can see, this condition is not a particularly smart condition - it only works when it’s March!

However, there are plenty of ways to improve the condition and make it more precise. Below are listed comparison operators that can be used in the condition:

Operators Description
== Equals
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
!= Not equal to

In addition, there are some logical operators:

Operators Description
&& And
| | Or
! Not

The operators can be used to develop more precise conditions, so now we can expand the above example to include all the spring months:

 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         var today = DateTime.Now;
 6         if (today.Month >= 3 && today.Month <= 5)
 7         {
 8             Console.WriteLine("Now it's spring!");
 9         }
10         else
11         {
12             Console.WriteLine("Now it's either winter, summer or autumn!");
13         }
14 
15         Console.ReadLine();
16     }
17 }

Let’s take a closer look at the extended condition:

1 today.Month >= 3 && today.Month <= 5

The condition can be translated into:

1 If the month is greater than or equal to 3,
2 	and the month is less than or equal to 5

Smart, eh? Operators play a significant role in many different parts of C#.

But it still only works with March, April and May. All other months are not yet covered by the condition. So let’s try to develop the condition a little more.

C# If-Else Ladder

Using else-if, we can expand the condition and make it work for all months:

 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         var today = DateTime.Now;
 6         if (today.Month >= 3 && today.Month <= 5)
 7         {
 8             Console.WriteLine("Now it's spring!");
 9         }
10         else if (today.Month >= 6 && today.Month <= 8)
11         {
12             Console.WriteLine("Now it's summer!");
13         }
14         else if (today.Month >= 9 && today.Month <= 11)
15         {
16             Console.WriteLine("Now it's autumn!");
17         }
18         else
19         {
20             Console.WriteLine("Now is winter!");
21         }
22         Console.ReadLine();
23     }
24 }

To write conditions is all about thinking logically and being methodical. The example above is pretty straightforward, but conditions can get very complex.

C# Switch Case

Another way of writing conditions is to use the switch method:

 1 switch (expression) 
 2 { 
 3     case 1: 
 4        statement
 5        break;	
 6     case 2: 
 7        statement
 8        break; 
 9     default:
10        statement
11        break;
12 }

This method is based on an expression and then lists different “answers” or “values” with related statements. The easiest way to explain the method is to show an example.

As you may remember from lesson 4, the function date(“w”) returns the current weekday. This can be used in an example where we write the name of the day (instead of a number):

 1 class Program
 2 {
 3     static void Main(string[] args)
 4     {
 5         var today = DateTime.Now;
 6         switch (today.Day)
 7         {
 8             case 1:
 9                 Console.WriteLine("Now it's Monday");
10                 break;
11             case 2:
12                 Console.WriteLine("Now it's Tuesday");
13                 break;
14             case 3:
15                 Console.WriteLine("Now it's Wednesday");
16                 break;
17             case 4:
18                 Console.WriteLine("Now it's Thursday");
19                 break;
20             case 5:
21                 Console.WriteLine("Now it's Friday");
22                 break;
23             case 6:
24                 Console.WriteLine("Now it's Saturday");
25                 break;
26             default:
27                 Console.WriteLine("Now it's Sunday");
28                 break;
29 
30         }
31         Console.ReadLine();
32     }
33 }

Often switch can be a good alternative to if-else conditions. What you should use in a given situation depends on which method you find easiest and most logical. Making your scripts logical and clear can be a great challenge.

C# Jump Statements

The jump statements include:

  • break
  • continue
  • goto
  • return (covered in later lessons)
  • throw (covered in later lessons)
  • break

C# Break

The ‘break’ statement breaks out of the ‘while’ and ‘for’ loops covered in previous lesson, and the ‘switch’ statements covered before in this lesson. The following code gives an example - albeit a very inefficient one - of how it could be used. The output of the loop is the numbers from 0 to 4.

1 int a = 0;
2 while (true)
3 {
4     System.Console.WriteLine(a);
5     a++;
6     if (a == 5)
7         break;
8 }

C# Continue

The ‘continue’ statement can be placed in any loop structure. When it executes, it moves the program counter immediately to the next iteration of the loop. The following code example uses the ‘continue’ statement to count the number of values between 1 and 100 inclusive that are not multiples of seven. At the end of the loop the variable y holds the required value.

1 int y = 0;
2 for (int x=1; x<101; x++)
3 {
4     if ((x % 7) == 0)
5         continue;
6     y++;
7 }

C# Goto

The ‘goto’ statement is used to make a jump to a particular labelled part of the program code. It is also used in the ‘switch’ statement described below. We can use a ‘goto’ statement to construct a loop, as in the following example (but again, this usage is not recommended):

1 int a = 0;
2 start:
3 System.Console.WriteLine(a);
4 a++;
5 if (a < 5)
6     goto start;
C# Conditions
Share this

Subscribe to Code with Shadman