The if
Statement
Starting by evaluating a Boolean expression, the if
statement can conditionally execute an embedded statement. Two forms exist, depending on whether you want to handle the negative case:
// Ignore when condition evaluates false.if (condition) statement-if-true// Also handle the false case.if (condition) statement-if-trueelse statement-if-false
Let’s look at an example that uses both branches:
static void Main(){ var rand = new Random(); int n = rand.Next(0, 100); PrintEvenOrNot(n);}static void PrintEvenOrNot(int n){ if (n % 2 == 0) { Console.WriteLine("Even"); } else { Console.WriteLine("Odd"); }}
In the Main
method, we’re using a random number generator to select a number between ...
Get C# 4.0 Unleashed now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.