C# Simplified, part 2: Methods & Programming Constructs - Different types of programming constructs in C#
(Page 4 of 6 )
Like all other programming languages, C# also offers programming constructs, namely if-else and switch-case. The usage of these constructs is similar to that of their Java and C++ counterparts, and is explained below in detail.
If-else
This is the popular decision making statement used in C#. It helps you to compare between two or more values. Its usage is shown in listing 2.7.
Listing 2.7
if(Condition)
{
Statements
}
else
{
Statements
}
In listing 2.8, two values are compared. If the value of X1 is greater than X2, the message "X1 is greater" will be displayed. Otherwise, the statement inside the else part will be printed as output.
Listing 2.8
using System;
class CompareIfElse
{
public static void Main()
{
int X1 = 50;
int X2 = 100;
if(X1>X2)
{
Console.WriteLine("X1 is greater");
}
else
{
Console.WriteLine("X2 is greater");
}
}
}
switch-case
This construct is also intended to be used for decision making, but it is generally regarded as an alternative to the if-else clause discussed above. This construct will be particularly useful for large programs, because it is difficult for the developers to debug several if-else branches. Its usage is shown in listing 2.9.
Listing 2.9
switch(expression)
{
case X:
Console.WriteLine("X is selected");
break;
case Y:
Console.WriteLine("Y is selected");
break;
default:
Console.WriteLine("Invalid Selection");
break;
}
When the expression matches with a case value, the respective statements will be printed. In listing 2.10, a value is declared as an integer type and its variable name is passed as a parameter to the switch() clause. The C# compiler looks for the relevant case entry. If it is found, the statements inside that case clause will be printed. If there is no valid case structure, the statements inside the default clause will be printed.
Listing 2.10
using System;
class SwitchCaseExample
{
public static void Main()
{
int day = 3;
switch(day)
{
case 1: Console.WriteLine("Today is Monday");
break;
case 2: Console.WriteLine("Today is Tuesday");
break;
case 3: Console.WriteLine("Today is Wednesday");
break;
default: Console.WriteLine("Invalid Entry");
break;
}
}
}
Next: Different types of looping statements in C# >>
More C# Articles
More By Anand Narayanaswamy