The if-else statement

Conditional statements are a basic component of many programming languages. They control program flow, depending on given conditions.

Consider the following scenario. We want to build a program that determines whether a user is an adult by checking their age. If the user is 18 or older, then they’re an adult.

Let’s first create a variable to obtain the user’s age.

Console.Write("What is your age? ");
int age = Convert.ToInt32(Console.ReadLine());

We now perform a check. If age is greater than 18, then we print “You are an adult!” Otherwise, we print “You are not yet an adult.”

Such checks can be done using the if-else statement in C#. The basic syntax is as follows:

if (condition)
	// Actions to be executed if the condition is true
	// Actions to be executed if the condition is false

The condition, in this context, is simply a bool value that holds either true or false:

Get hands-on with 1200+ tech skills courses.