if, else if, else and the ternary operator
An if statement runs a block only when its condition is true. The condition must be a bool — C# will not treat 0, null or an empty string as false the way C or JavaScript do. Chain alternatives with else if; the first true condition wins and the rest are skipped. A final else catches everything left.
int[] scores = { 95, 82, 67, 40 };
foreach (int score in scores)
{
string grade;
if (score >= 90)
grade = "A";
else if (score >= 75)
grade = "B";
else if (score >= 50)
grade = "C";
else
grade = "F";
Console.WriteLine($"{score} -> {grade}");
}
int age = 20;
bool hasTicket = true;
if (age >= 18 && hasTicket)
{
Console.WriteLine("You may enter.");
}95 -> A
82 -> B
67 -> C
40 -> F
You may enter.Add an A+ grade for 98 and above. Where does the new branch have to go, and why?
if controls only the next single statement. Add a second indented line later and it runs every time, whatever the condition — the indentation lies. Most C# style guides (and dotnet format rules) require braces on every branch for that reason; the short form above is fine only for one-line branches.The ternary operator condition ? a : b is an expression: it produces a value, so you can assign it, return it or put it inside an interpolated string. Use it for a simple choice between two values, and fall back to if when either side needs more than one step.
int items = 1;
Console.WriteLine($"{items} item{(items == 1 ? "" : "s")}");
items = 3;
Console.WriteLine($"{items} item{(items == 1 ? "" : "s")}");
decimal total = 1200m;
decimal shipping = total >= 999m ? 0m : 49m;
Console.WriteLine($"Shipping: {shipping}");
int temp = 31;
string feel = temp > 30 ? "hot" : temp > 15 ? "mild" : "cold";
Console.WriteLine(feel);1 item
3 items
Shipping: 0
hotInside an interpolated string, a ternary needs parentheses, because : would otherwise start a format specifier.
CS0029: = instead of == in a condition
int x = 5;
if (x = 5)
Console.WriteLine("five");Program.cs(2,5): error CS0029: Cannot implicitly convert type 'int' to 'bool'= is assignment, and x = 5 is an expression whose value is the int 5. An if needs a bool, and C# never treats a number as true or false. In C this bug compiles and always runs the branch; in C# it cannot.
Use == to compare.
int x = 5;
if (x == 5)
Console.WriteLine("five");