If Statements
Why use If?
Use an if statement to check whether you want to execute some code based on a decision. For example only children aged 12 or over can be admitted to a theme park:
if (age > 12)
{
MessageBox.Show("You may enter the theme park");
}
Note: code that code to run if the condition is true is grouped in curly braces.
Using If with Else
You can use the word else
to mean "otherwise". For example, children under 12 are not allowed into the theme park:
if (age > 12)
{
MessageBox.Show("You may enter the theme park.");
}
else
{
MessageBox.Show("You are too young to enter the theme park.");
}
Using Else If
You can use the word else if
to mean "otherwise if". For example, we could check if children under 12 have a parent or guardian (PG) with them:
if (age > 12)
{
MessageBox.Show("You may enter the theme park.");
}
else if (PG_Present == true)
{
MessageBox.Show("You may enter the theme park. But please stay with your parent or guardian");
}
else
{
MessageBox.Show("You are too young to enter the theme park.");
}
Using multiple Else Ifs
You can use the word more than one else if
statements together. For example, we could check if children under 12 have a parent or guardian (PG) with them. If they don't have a parent or guardian, check if one is available near by.
if (age > 12)
{
MessageBox.Show("You may enter the theme park.");
}
else if (PG_Present == true)
{
MessageBox.Show("You may enter the theme park. But please stay with your parent or guardian");
}
else if (PG_Nearby == true)
{
MessageBox.Show("Please get your parent of guardian.");
}
else
{
MessageBox.Show("You are too young to enter the theme park without your parent or guardian.");
}