Conditional Statements in C#: if , if..else, Nested if, if-else-if

Conditional Statements in C#: if , if..else, Nested if, if-else-if

29 Apr 2024
Beginner
9.52K Views
13 min read
Learn with an interactive course and practical hands-on labs

Free C# Foundation Course: Learn C# In 21 Days

Conditional Statements in C#: An overview

C# is a powerful and versatile programming language that provides developers with various tools and constructs to implement conditional logic. One of the fundamental constructs in C# is the if-else statement in C#. In this comprehensive guide, we will explore the intricacies of using conditional statements effectively in C#.In this C# Tutorial, we will explore more about jump Statements in C# which will include Understanding how "break," "continue," "return," “throw” and "goto" statements work.

What are Conditional Statements in C#? 

Conditional statements in C# are used to make decisions in your code based on certain conditions or expressions. These statements allow you to control the flow of your program by executing different blocks of code depending on whether a condition is true or false. Conditional statements are fundamental to writing logic and creating responsive, dynamic programs.

Different Types of Conditional Statements in C#

. C# provides several conditional statements, which include:

  • Simple C# if statement
  • If-else statement in C#
  • If-else-if statement in C#
  • Nested if statement in C#

Simple C# if statement

In C# if statement is a control structure used to execute a block of code conditionally. It allows you to specify a condition, and if that condition evaluates to true, the code block within the "if" statement is executed.

Syntax


 if (condition)
{
 // Code to be executed if the condition is true
}

Example

Let's elaborate this on C# Compiler:
  
using System;

class Program
{
    static void Main()
    {
        int age = 25;
        
        if (age >= 18)
        {
            Console.WriteLine("You are an adult.");
        }
    }
}

Explanation

This C# code checks if the age variable is greater than or equal to 18, which is the legal age of adulthood in many places. If the condition is true, it prints "You are an adult." This code essentially determines and outputs whether the person is considered an adult based on their age.

Output

 You are an adult.

Read More - C# Interview Questions And Answers

If-else statement

The if-else statement allows us to provide an alternative block of code to execute if the condition is false. An if-else statement in C# is a control structure that allows you to conditionally execute different blocks of code based on a specified condition. It is used to make decisions in your program based on whether a particular condition is true or false.

Syntax

  if (condition)
{
 // Code to execute if the condition is true
}
else
{
 // Code to execute if the condition is false
}

Example


using System;

class Program
{
    static void Main()
    {
        int temperature = 25;

        if (temperature > 30)
        {
            Console.WriteLine("It's hot outside.");
        }
        else
        {
            Console.WriteLine("It's not too hot.");
        }
    }
}

Explanation

This C# code evaluates the temperature variable to determine if it's hot outside. If the temperature is greater than 30 degrees, it prints "It's hot outside." Otherwise, it prints "It's not too hot." In this case, it prints the latter because the temperature is 25 degrees.

Output

 It's not too hot.

If-else-if statement/ if-else-if Ladder in C#

In C#, an "if-else-if" statement is a control structure that allows you to execute different blocks of code based on multiple conditions. It provides a way to test multiple conditions sequentially and perform different actions depending on the outcome of each condition.

Syntax


if (condition1)
{
 // Code to execute if condition1 is true
}
else if (condition2)
{
 // Code to execute if condition1 is false and condition2 is true
}
else
{
 // Code to execute if all conditions are false
}

Example

 
 using System;

class Program
{
    static void Main()
    {
        int score = 75;

        if (score >= 90)
        {
            Console.WriteLine("You got an A.");
        }
        else if (score >= 80)
        {
            Console.WriteLine("You got a B.");
        }
        else if (score >= 70)
        {
            Console.WriteLine("You got a C.");
        }
        else
        {
            Console.WriteLine("You need to improve your score.");
        }
    }
}

Explanation

This C# code evaluates a score variable to determine a corresponding grade. It uses a series of if-else if statements to check if the score falls within specific ranges. It prints a message indicating the grade (A, B, C) based on the score, and if none of the conditions match, it advises improvement. In this case, it prints "You got a C" because the score is 75.

Output

 You got a C.

Nested if statement

The nested if statement in C# refers to the concept of having one if statement inside another if statement. It allows for more complex decision-making logic by evaluating multiple conditions in a hierarchical manner.

Syntax


 if (condition1)
{
 // Code to be executed if condition1 is true
 if (condition2)
 {
 // Code to be executed if condition1 and condition2 are true
 }
 else
 {
 // Code to be executed if condition1 is true, but condition2 is false
 }
}
else
{
 // Code to be executed if condition1 is false
}

Example

  
using System;

class Program
{
    static void Main()
    {
        int age = 25;
        bool isStudent = true;

        if (age >= 18)
        {
            if (isStudent)
            {
                Console.WriteLine("You are a student and an adult.");
            }
            else
            {
                Console.WriteLine("You are an adult.");
            }
        }
        else
        {
            Console.WriteLine("You are not an adult.");
        }
    }
}

Explanation

This C# in the C# Editor code checks two conditions. It first checks if the age variable is greater than or equal to 18. If true, it further checks whether the student variable is true. Depending on the results, it prints messages indicating whether the person is an adult, a student, or both, with appropriate combinations of conditions.

Output

 You are a student and an adult.
Conclusion

In conclusion, the if-else statement in C# is a fundamental and powerful control structure that plays a pivotal role in decision-making within your code. Its versatility allows developers to create branching logic, enabling applications to respond dynamically to different conditions. By mastering the if-else statement, you gain the ability to write more sophisticated and responsive C# programs So, whether you're a beginner or an experienced developer, understanding and leveraging the if-else statement is a crucial skill for success in C# programming. Also, Consider our C# Programming Course for a better understanding of all C# concepts.

Take our Csharp skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this