Title here
Summary here
Branching with if
and else
in C# is straightforward.
using System;
class Program
{
static void Main()
{
// Here's a basic example.
if (7 % 2 == 0)
{
Console.WriteLine("7 is even");
}
else
{
Console.WriteLine("7 is odd");
}
// You can have an if statement without an else.
if (8 % 4 == 0)
{
Console.WriteLine("8 is divisible by 4");
}
// Logical operators like && and || are often useful in conditions.
if (8 % 2 == 0 || 7 % 2 == 0)
{
Console.WriteLine("either 8 or 7 are even");
}
// A statement can precede conditionals; any variables
// declared in this statement are available in the current
// and all subsequent branches.
int num = 9;
if (num < 0)
{
Console.WriteLine($"{num} is negative");
}
else if (num < 10)
{
Console.WriteLine($"{num} has 1 digit");
}
else
{
Console.WriteLine($"{num} has multiple digits");
}
}
}
To run the program, save it as IfElse.cs
and use the C# compiler:
$ csc IfElse.cs
$ IfElse.exe
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
Note that in C#, parentheses are required around conditions, and braces are also required for multi-line code blocks. For single-line code blocks, braces are optional but recommended for clarity.
C# does have a ternary operator (?:
), which can be used for simple conditional expressions:
string result = (7 % 2 == 0) ? "7 is even" : "7 is odd";
Console.WriteLine(result);
This can be useful for simple conditions, but for more complex logic, a full if
statement is often more readable.