Branching and Looping in C#, Part 1 - Nesting
(Page 3 of 6 )
Of course you can nest if statements as much as you want. Let's take a look:
using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
Console.WriteLine("Please type a number");
int x = Convert.ToInt32(Console.ReadLine());
if(x % 2 == 0)
{
if(x < 1000)
{
Console.WriteLine("this is an EVEN number");
}
else
{
Console.WriteLine("this is a big EVEN number");
}
}
else
{
if(x < 1000)
{
Console.WriteLine("this is an ODD number");
}
else
{
Console.WriteLine("this is a big ODD number");
}
}
Console.ReadLine();
}
}
}
As you can see, I have added nested if statements to test if the number is greater than or less than 1000, and I print to the console a line in each case. One thing to note about VS.NET is its indentation scheme:

You can tell that there's only one top level if statement associated with an else statement, and each statement has a nested if statement, too. VS.NET will indent if statements automatically.
Next: Combining else With if >>
More C# Articles
More By Michael Youssef