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, ...

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.