Signup/Sign In
LAST UPDATED: JUNE 20, 2023

Control Statements in C# - if, else, switch etc

Technology #c#

    The control statements are used to control the flow of execution of the program. If you want to execute a specific block of instructions only when a certain condition is true, then control statements are useful. If you want to execute a block repeatedly, then loops are useful.

    C# control statements - if, else, else if, switch

    We will cover the topic of loops in C# in the next tutorial. In this tutorial, we will cover the various control statements in C# along with code examples to understand how to use them in your programs.

    1. if...else statement

    2. if...else if...else statements

    3. switch statement

    4. goto statement

    Now, we will see the implementation of each control statement.


    If, If-else, Switch Case Control Statements in C#

    1. if...else statement

    if else statement in c#

    The if statement is used to check for a condition and based on it decide whether or not to execute a code block. The if code block is executed only if the condition is true otherwise further instruction or else block gets executed. You can write nested if blocks if required. The following diagram shows the basic flow of a default if-else statement. It is not mandatory to have an else block after an if block. The else statement is used to specify the code which has to be executed if the condition doesn't return true.

    Let's see a practical implementation of if statement.

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                int i = 100;
                if(i > 0)
                {
                     Console.WriteLine("Given number is positive!");
                }
                else
                {
                     Console.WriteLine("Given number is negative!");
                }
                Console.ReadKey();
            }
        }
    }

    This program checks if the value of i is greater than 0 using an if statement.

    If the condition i > 0 evaluates to true, the code inside the if block will be executed. In this case, it prints the message "Given number is positive!" and If the condition i > 0 evaluates to false, the code inside the else block will be executed. It prints the message "Given number is negative!" to the console.

    Output:

    Given number is positive!

    Try running the above program by providing a negative value to i variable, the else code will get executed.


    2. if...else if...else statement

    If we have to specify two conditions that are related to each other, we can use the else if statement to specify the second condition and its related code block. We can use multiple else if blocks to add multiple conditions but it requires at least one if block at the beginning, we can't directly write else and else if statements without having any if block.

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                int i = 0;   // Zero is neutral in nature
                if(i > 0)
                {
                    Console.WriteLine("Given number is positive!");
                }
                else if(i < 0)
                {
                    Console.WriteLine("Given number is negative!");
                }
                else
                {
                    Console.WriteLine("Given number is neither positive nor negative!");
                }
                Console.ReadKey();
            }
        }
    }

    The first condition if (i > 0) checks if the value of i is greater than 0. If it evaluates to true, the code inside the if block will be executed.

    If the first condition if (i > 0) evaluates to false, the program proceeds to the next condition which checks if the value of i is less than 0. If it evaluates to true, the code inside the else if block will be executed and will print the message "Given number is negative!" to the console.

    If both the conditions if (i > 0) and else if (i < 0) evaluate to false, it means that the value of i is 0. In this case, the code inside the else block will be executed.

    Output:

    Given number is neither positive nor negative!


    3. switch statement

    The switch statement executes only one statement from multiple given statements associated with conditions. If any condition returns true, then the code statements below it get executed. The following diagram shows the basic flow of a switch statement.

    switch statement in c sharp

    Let's see the practical implementation of the switch statement,

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                Console.WriteLine("1.Additon\n2.Subtraction\n3.Division\nEnter your choice:");
                int c = Convert.ToInt32(Console.ReadLine());
                switch(c)
                {
                    case 1: Console.WriteLine("\nAddition selected!"); break;
                    case 2: Console.WriteLine("\nSubtraction selected!"); break;
                    case 3: Console.WriteLine("\nDivision selected!"); break;
                    default: Console.WriteLine("\nYour choice not found!"); break;
                }
                Console.ReadKey();
            }
        }
    }

    The code uses a switch statement to perform different actions based on the value of c. If c matches the value 1, the code inside case 1: block is executed.and will print the message "\nAddition selected!" to the console.

    If c matches the value 2, the code inside case 2: block is executed and it prints the message "\nSubtraction selected!" to the console. If the value is 3, the code inside case 3: block is executed and If none of the case labels match the value of c, the code inside the default: block is executed.

    Output:

    1.Additon
    2.Subtraction
    3.Division
    Enter your choice: 4
    
    Your choice not found!

    As you can see in the above code example, if none of the cases is matched, then the default case will be executed. If your choice is 1 then only case 1 will be executed and other cases will not execute not even the default case. The break statement is used to come out of any switch case, if we remove the break statements from all the case blocks, then after the execution of the case for which the condition is true, the default condition will also get executed.


    4. goto statement

    The goto statement is used to transfer the control from a loop or switch case to a specified label. It is also known as a jump statement. It is generally recommended to avoid using it as it makes the program more complex. In the following example, if the user is logged in then we have directly jumped our code to the success label.

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                string user = "login";
    
                if(user=="login")
                {
                    goto success;
                }
    
                success:
                Console.WriteLine("Welcome to Studytonight!");
                Console.ReadKey();
            }
        }
    }

    Output:

    Welcome to Studytonight!

    Conclusion

    In this tutorial, we learned about control statements which included if, else and else if statements. We can also use these control statements in a nested form which means we can have any number of if block inside an if block, or if...else block inside an if block or else block or an else if block, or we can have multiple else if blocks with if and else blocks. In simpler words, we can say that these control statements are very flexible and can be used in any form very easily.

    Frequently Asked Questions(FAQs)

    1. What is a control statement in C#?

    In C#, a control statement is a programming construct that allows you to control the flow of execution in your code based on certain conditions. They enable decision-making and branching, ensuring that different parts of your code are executed based on specific criteria.

    2. What is the if statement in C#?

    The if statement is a fundamental control statement in C#. It evaluates a condition and executes a block of code if the condition is true. It can also be extended with an optional else clause to handle the case when the condition is false.

    3. What is the switch statement in C#?

    The switch statement in C# provides an elegant way to handle multiple possible values of a variable or expression. It allows you to compare a value against several cases and execute the code block associated with the first matching case.

    4. Can I use multiple conditions in an if statement?

    Yes, you can use multiple conditions in an if statement by combining them with logical operators such as && (AND) and || (OR). This allows you to create complex conditions that consider multiple factors when making decisions in your code.

    5. Are there any best practices for using control statements in C#?

    Some best practices for using control statements in C# include writing clear and concise conditions, using proper indentation and formatting to enhance readability, avoiding nested control statements when possible, and ensuring that your code has appropriate error handling and fallback options. Additionally, it's crucial to thoroughly test your control statements to ensure they behave as expected in different scenarios.

    You may also like:

    Subject Matter Expert of C# Programming at Studytonight.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS