C# If and Else
An if statement is code that runs its block only when its condition is true. Adding else gives the false case its own block.
An if block
The block runs because the condition is true. Nothing runs when the condition is false.
using System;
class Program
{
static void Main(string[] args)
{
int age = 20;
if (age >= 18)
{
Console.WriteLine("Adult");
}
}
}If and else
The guess does not match the secret number. The else block runs instead.
using System;
class Program
{
static void Main(string[] args)
{
int secret = 7;
int guess = 42;
if (guess == secret)
{
Console.WriteLine("Correct");
}
else
{
Console.WriteLine("Try again.");
}
}
}An else if chain
The chain tests each condition in order. The first true condition wins.
using System;
class Program
{
static void Main(string[] args)
{
int score = 85;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F");
}
}
}A one line choice
The ?: operator tests the condition in parentheses. It gives "Pass" here because the score reaches 50.
using System;
class Program
{
static void Main(string[] args)
{
int score = 72;
string result = (score >= 50) ? "Pass" : "Fail";
Console.WriteLine(result);
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
int temperature = 14;
if (temperature >= 25)
{
Console.WriteLine("Wear light clothes.");
}
else if (temperature >= 15)
{
Console.WriteLine("Wear a light jacket.");
}
else
{
Console.WriteLine("Wear a warm coat.");
}
}
}Key points
- The condition sits in parentheses after if.
- The condition must give a bool value.
- Use else to run a block when the condition is false.
- Use else if to test another condition after a false one.
- Only the first true branch in a chain runs.
- The ?: operator picks one of two values from a condition.
In this example, temperature is 14. The first check asks if 14 is at least 25, and it is not. The second check asks if 14 is at least 15, and it is not. The else block runs. The printed line is "Wear a warm coat.".
Note
An if condition cannot be a number, and 1 does not stand for true in C#.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C# Compiler
Exercise
When does an else block run?