C# If...Else
Conditional statements.
C# If...Else
C# supports the usual logical conditions from mathematics:
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
- Equal to: a == b
- Not equal to: a != b
You can use these conditions to perform different actions for different decisions.
Conditional Statements
C# has the following conditional statements:
- Use
ifto specify a block of code to be executed, if a specified condition is true - Use
elseto specify a block of code to be executed, if the same condition is false - Use
else ifto specify a new condition to test, if the first condition is false - Use
switchto specify many alternative blocks of code to be executed
Ternary Operator
There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.
Syntax: variable = (condition) ? expressionTrue : expressionFalse;
Examples
The if Statement
Basic if condition.
using System;
class Program
{
static void Main(string[] args)
{
if (20 > 18)
{
Console.WriteLine("20 is greater than 18");
}
}
}The else Statement
Executing code when condition is false.
using System;
class Program
{
static void Main(string[] args)
{
int time = 20;
if (time < 18)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
}
}The else if Statement
Handling multiple conditions.
using System;
class Program
{
static void Main(string[] args)
{
int time = 22;
if (time < 10)
{
Console.WriteLine("Good morning.");
}
else if (time < 20)
{
Console.WriteLine("Good day.");
}
else
{
Console.WriteLine("Good evening.");
}
}
}