Page Content

Tutorials

What Are The Conditional Statements In C# With Code Examples

Conditional Statements In C#

Basic programming structures called conditional statements let your program run different code blocks depending on whether or not specific conditions are met. These fall into two primary categories in C#: unconditional execution and conditional execution. If, if-else, if-else-if, if-else-if ladder, nested if statements, and switch statements are examples of conditional execution statements that will be the main topic of this response.

In C#, conditions have to resolve to bool (Boolean) values. Bool-type data cannot be cast directly or implicitly to any other data type other than object since C# has a native bool data type. When an if statement uses the assignment operator (=) rather than the equality operator (==), the C# compiler will detect this common error.

if statement

If a given condition is met, a block of code is executed using the if statement.

Syntax:

if( boolean_expression (Or) condition)
{
True-block-statement(s);

Behavior: The “body” of the code, enclosed in curly brackets {}, is run if the Boolean statement evaluates to true. It skips the body if the expression is false.

Important Note: In contrast to certain other languages (such as C language and C++), Boolean expressions in C# must be clearly true or false and cannot be numbers.

Good Practice: An if statement’s body should always be enclosed in curly brackets {}, even if it only has one statement. This technique makes code less deceptive and makes it easier to read.

Example: To find the bigger of two numbers:

using System;
namespace DecisionMaking
{
    class Program
    {
        static void Main()
{
    Console.WriteLine("Enter two numbers.");
    Console.Write("Enter first number: ");
    int firstNumber = int.Parse(Console.ReadLine());
    Console.Write("Enter second number: ");
    int secondNumber = int.Parse(Console.ReadLine());
    int biggerNumber = firstNumber;
    if (secondNumber > firstNumber) // Boolean expression
    {
        biggerNumber = secondNumber;
    }
    Console.WriteLine("The bigger number is: {0}", biggerNumber);
}
}
}

Output

Enter two numbers.
Enter first number: 3
Enter second number: 5
The bigger number is: 5

if-else statement

You can use the if-else statement to determine whether a condition is true or false and then execute one of two different blocks of statements.

Syntax

{
True-block-statement(s);
}
else
{
False-block-statement(s) will execute if the Boolean expression is false */
}

Behavior: Evaluation is done on the Boolean expression. If it is true, the else block is bypassed and the if block is run. If it is false, the if block is skipped and the else block is run.

Example: Checking if a number is less than 20:

using System;
namespace DecisionMaking
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 100;
            if (a < 20)
                Console.WriteLine("a is less than 20");
            else
                Console.WriteLine("a is not less than 20");
            Console.WriteLine("value of a is : {0}", a);
        }
    }
}

Output

a is not less than 20
value of a is : 100

Nested if statement

In a nested if statement, one if or if-otherwise statement is inserted inside the body of another if or else condition.

Behavior: Only when the outer (enclosing) condition of the inner conditional expression evaluates to true will it be evaluated and perhaps executed. The closest preceding if clause is matched by each else clause.

Good Practice: Generally speaking, nesting more than three levels is not a smart idea. To make your code easier to read and maintain, think about separating certain sections into distinct methods if your logic calls for deeper nesting.

Example: Comparing two numbers in two steps:

using System;
namespace DecisionMaking
{
    class Program
    {
        static void Main(string[] args)
        {
           int first = 5;
int second = 3;
if (first == second)
{
    Console.WriteLine("These two numbers are equal.");
}
else
{
    if (first > second) // Nested if statement
    {
        Console.WriteLine("The first number is greater.");
    }
    else
    {
        Console.WriteLine("The second number is greater.");
    }
}
}
}
}

Output

The first number is greater.

if-else-if ladder

An “if-else-if ladder,” as this technique is commonly known, is used to run a single block of code from a list of alternative options.

Behavior: Sequentially, the conditions are assessed from top to bottom. It executes the block of statements linked to the first Boolean expression that evaluates to true. Following that, all if and else blocks are bypassed. If there is a final else block, it is executed if none of the if or else if conditions are true.

Requirement: At least one initial if block is required; you cannot begin with an else or else if statement.

Important Note: Because control bypasses subsequent tests when a condition is satisfied, the sequence in which the conditions are placed within an if-else construct is essential.

Good Practice: Although helpful for a variety of scenarios, a switch-case statement is occasionally a more effective and understandable option.

Example: Assigning a message based on a score:

using System;
namespace DecisionMaking
{
    class Program
    {
        static void PrintPassOrFail(int score)
        {
            if (score > 100) // If score is greater than 100
            {
                Console.WriteLine("Error: score is greater than 100!");
            }
            else if (score < 0) // Else If score is less than 0
            {
                Console.WriteLine("Error: score is less than 0!");
            }
            else if (score >= 50) // Else if score is greater or equal to 50
            {
                Console.WriteLine("Pass!");
            }
            else // If none above, then score must be between 0 and 49
            {
                Console.WriteLine("Fail!");
            }
        }
        static void Main(string[] args)
        {
            // --- Examples of how to use the PrintPassOrFail method ---
            PrintPassOrFail(75);  // Should print "Pass!"
            PrintPassOrFail(40);  // Should print "Fail!"
            PrintPassOrFail(105); // Should print "Error: score is greater than 100!"
            PrintPassOrFail(-10); // Should print "Error: score is less than 0!"
            PrintPassOrFail(50);  // Should print "Pass!"
            PrintPassOrFail(0);   // Should print "Fail!"
        }
    }
}

Output

Pass!
Fail!
Error: score is greater than 100!
Error: score is less than 0!
Pass!
Fail!

switch statement

A multi-way branch statement, the switch statement offers a productive method of allocating execution to various code segments according to the value of an expression.

Supported Expression Types: An integer type (int, char, byte, or short), an enumeration type, or a string type can all be used for the switch expression. It is incompatible with floating-point numbers and arrays.

Behavior: Different case labels are used to compare the value of the switch expression. Should a match be discovered, the statements related to that instance are carried out. If there is a default section, control is moved there if the case label does not match.

break Requirement: “Silent fall-through” from one case section to the next is not possible with C#. The switch statement must be terminated by an explicit jump statement, usually break, at the end of each case statement (if it contains code). There will be a compile-time error if a break is not included.

default Statement: Though it is advised to put the default statement at the end for readability, it is optional and can be positioned anywhere in the switch block. Several default statements are prohibited.

Case Values: Case label values cannot be variables; they must be literals or constants. Also prohibited are duplicate case values.

Multiple Labels: Listing case labels one after the other without break statements allows you to combine them together if they share a block of code.

Example: A switch statement to check a grade:

using System;
namespace DecisionMaking
{
    class Program
    {
        static void Main(string[] args)
        {
            char grade = 'B';
            switch (grade)
            {
                case 'A':
                    Console.WriteLine("Excellent!");
                    break;
                case 'B':
                    Console.WriteLine("Well done");
                    break;
                case 'C':
                    Console.WriteLine("Pretty good");
                    break;
                case 'D':
                    Console.WriteLine("Passed");
                    break;
                case 'F':
                    Console.WriteLine("Not so good");
                    break;
                default:
                    Console.WriteLine("Invalid grade");
                    break;
            }
            Console.WriteLine("Your grade is {0}", grade);
        }
    }
}

Output

Well done
Your grade is B

You can also read Expressions In C#: From Basic To Advance Level With Examples

Agarapu Geetha
Agarapu Geetha
My name is Agarapu Geetha, a B.Com graduate with a strong passion for technology and innovation. I work as a content writer at Govindhtech, where I dedicate myself to exploring and publishing the latest updates in the world of tech.
Index