Home »
.Net »
C# Programs
C# - Example of Multiple if else Statement
C# multiple if else statement example: Here, we are writing a C# - Example of Multiple if else Statement.
Submitted by IncludeHelp, on April 07, 2019 [Last updated : March 17, 2023]
Multiple if else Statement
Like other programming languages, multiple if else statement in C# is used to execute one code block written in multiple different blocks based on the condition. We can check multiple conditions by having their own code block sections and at a time only one code block section executes. If all conditions are false, then else block code section executes.
Syntax
if(test_condition1){
//code section 1
}
else if(test_condition2){
{
//code section 2
}
else if(test_condition3){
//code section 3
}
...
else{
//else code section
}
Any number of tests can be checked, if any condition is true, statements written associated with that code section will be executes. If no one is true, then statements written in "else code section" will be executed.
Example 1: C# program to demonstrate the example of multiple if-else
Here, we are asking for an integer input – and checking whether input integer is positive value, negative value or a zero
// C# program to demonstrate example of
// multiple if else statement
using System;
using System.IO;
using System.Text;
namespace IncludeHelp {
class Test {
// Main Method
static void Main(string[] args) {
//input an integer number and check whether
//it is postive, negative or zero
int number;
Console.Write("Enter an integer number: ");
number = Convert.ToInt32(Console.ReadLine());
//checking conditions
if (number > 0)
Console.WriteLine("{0} is a positive number", number);
else if (number < 0)
Console.WriteLine("{0} is a negative number", number);
else
Console.WriteLine("{0} is a Zero", number);
//hit ENTER to exit the program
Console.ReadLine();
}
}
}
Output
Enter an integer number: -123
-123 is a negative number
Example 2: C# program to demonstrate the example of multiple if-else
Here, we are asking for a gender – and checking whether input gender is "Male", "Female" or "Unspecified gender".
// C# program to demonstrate example of
// multiple if else statement
using System;
using System.IO;
using System.Text;
namespace IncludeHelp {
class Test {
// Main Method
static void Main(string[] args) {
//input gender and check for "Male", "Female" or "Unspecied gender"
string gender = "";
Console.Write("Enter gender: ");
gender = Console.ReadLine();
if (gender.ToUpper() == "MALE")
Console.WriteLine("He is male");
else if (gender.ToUpper() == "FEMALE")
Console.WriteLine("She is female");
else
Console.WriteLine("Unspecified gender");
//hit ENTER to exit the program
Console.ReadLine();
}
}
}
Output
First run:
Enter gender: male
He is male
Second run:
Enter gender: FEMale
She is female
Third run:
Enter gender: Don't know
Unspecified gender
C# Basic Programs »