C# can make choices with data. This data (variables) are used with a condition: if statements start with a condition. A condition may be (x > 3), (y < 4), (weather = rain).

What do you need these conditions for? Only if a condition is true, code is executed.

If statements are present in your everyday life, some examples:

  • if (elevator door is closed), move up or down.
  • if (press tv button), next channel

If statements in C#

Example

The program below is an example of an if statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;

namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
int x = 3;

if (x > 2){
Console.WriteLine("condition is true");
Console.ReadKey();
}
}
}
}

csharp runs the code block only if the condition (x >2) is true. If you change variable x to any number lower than two, its codeblock is not executed.

Else

You can execute a codeblock if a condition is not true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;

namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
int x = 1;

if (x > 2){
Console.WriteLine("condition is true");
Console.ReadKey();
} else {
Console.WriteLine("condition is not true");
Console.ReadKey();
}
}
}
}

Exercises

  1. Make a program that divides x by 2 if it’s greater than 0
  2. Find out if if-statements can be used inside if-statements.