”C# if-else” statements are used to check the exactitude of a condition, based on which a code executes its next step. All the programmers should be well acquainted with these “C# if-else statements”.

Similar to all other programming languages, in C# also the “if-else statement” is used for checking whether a condition is true or not. We basically provide a condition statement with our ‘if block’, write some code under the ‘if’ block, and if the condition gets satisfied, then our program will execute the code under the ‘if’ block.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

Now, what if the condition doesn’t get satisfied? 

If we only use the if statement and the condition under “if statement” is not satisfied, then our program will return nothing. That means we will not get any output. In such cases, we write some code under our else statement such that if the “if statement” doesn’t get satisfied, then the code under “else statement” will execute.

If Statement

The C# if statement of “C# if-else” tests the condition; it is executed when a condition is true.

Example:

In this example, we will see if a person is eligible to vote, taking into account his age. 

// C# program to demonstrate if-else statement

using System;

class practice{

static public void Main()

{

    // Declaring and initializing variables

    int age = 20;

    // If statement

    if (age >= 18)

    {

        Console.WriteLine("The person can vote");

    }

}

C_Sharp_if-else_1

In the above program, we noticed that the person’s age was 20 (>=18). Therefore, the output we got is “The person can vote”.

If…else Statement

Now, in the same example,  let’s add code with else statement (for age<18).

// C# program to demonstrate if-else statement

using System;

class practice

    static public void Main()

    { 

        // Declaring and initializing variables

        int age = 10;

        // If statement

        if (age >= 18)

        {

            Console.WriteLine("The person can vote");

        }

        //else statement

        else

        {

            Console.WriteLine("The person can't vote");

        } 

    }

}

C_Sharp_if-else_2 

As you can see, the given age is not satisfying the if block condition; it will execute the else block code, and as a result, it will give an output “The person can’t vote”. 

Hence, we can conclude that the block of code inside the else statement will be executed if the expression is evaluated to false.

Now let’s talk about another statement called “else if” with “if” and “else” statement in “C# if-else”. 

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

If…else…if Statement

As we have seen, the else blocks get checked after the if blocks, and when the condition under the if block returns false, only then do we jump to the else blocks. 

In this section, we'll discuss a new block called the "else if" block, which is always placed after if blocks. 

There can be multiple else if blocks, and only when the condition statement under the if block returns false, we go for checking the condition statement in the else if block; if that condition also returns false, then we go to the else if block and so on;  if none of them returns true, then we go to the else block.

Example:

Suppose we are given two conditions, like if a person’s age is <18(under if block), then he/she should go to school, and if the age is >=18 and <60(under else if block), then he/she should go to party otherwise (under else block) he/she should stay at home and take rest. That means if the first given statement is not true, then only our condition statement under the “else if” block will be checked, and if the condition is not satisfied, then it will go to the else block and will execute the code under it.

// C# program to demonstrate if-else statement

using System;

class practice

{

    static public void Main()

    { 

     // Declaring and initializing variables

    int age = 26; 

    // else if statement

    if (age < 18)

    {

        Console.WriteLine("The person should go to school and study");

    }

    //else statement

    else if(age>=18 && age<60){

        Console.WriteLine("The person should go to party and enjoy life");

    }

    else{

         Console.WriteLine("The person should stay at home and take rest");

    } 

    }

}

C_Sharp_if-else_3.

In the above example we can see that the condition under the first if block returns false because the given age is not less than 18 , so then we go for checking the condition statement to the next else if block and here in this block the condition statement gets satisfied because the given age is 26 and it is greater than and equal to 18 and and less than 60 , so the  else if block returns true and we will get the output statement that “The person should go to party and enjoy life”. So this is how we check the conditions under if , else if and if blocks respectively .

Nested if-else

Now, there’s another concept in “C# if else” called “nested if-else”. 

In nested if-else, an if...else statement can exist within another if...else statement. It is like a condition under a condition; that is, if a condition gets satisfied, then we check for another condition under that former condition. 

Example:

Let’s say if a person’s age is <18 (if statement), then it will go under that condition block, and it will again check; if his age is <=16, then he goes to either primary or secondary school (if statement under the first if block under the former if block) otherwise he goes to higher secondary school (for the else block under the former if block).

// C# program to demonstrate if-else statement

using System;

class practice

    static public void Main()

    {

        // Declaring and initializing variables

        int age = 15;

        // else if statement

        if (age <= 18)

        {

            //nested if else statement

            if (age <= 16)

            {

                Console.WriteLine("He/she either goes to primary or to secondary school");

            }

            else

            {

                Console.WriteLine("He/she goes to higher secondary school");

            }

        }

    }

}

C_Sharp_if-else_4. 

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Conditional Operators in if

As we know, “C# if-else” is generally used for examining conditions, so for that purpose, we use many conditional operators in “C# if-else”, such as:

  • greater than (“>”) - this checks whether one value is greater than the other value or not.
  • lesser than (“<”) - this checks whether one value is lesser than another value or not. 
  • greater than and equal to (“>=”) - this returns true if the formal value is greater than or equal to the latter value.
  • lesser than and equal to (“<=”) - this returns true if the formal value is lesser than or equal to the latter value.
  • equals to (“==”) - this returns true if both the values become equal. 
  • not equal to (“!=”) - this returns true if the two values are not equal.

// C# program to demonstrate if-else statement

using System;

class practice

    static public void Main()

    {

  int x = 10, y = 20;

        if (x > y)

        {

            Console.WriteLine("x is greater than y");

        }

        int z = 20;

        if (z == y)

        {

            Console.WriteLine("z is equal to y");

        }

        z = 40;

        if (z >= y)

        {

            Console.WriteLine("z is greater than or equal to y");

        }

        if (y <= z)

        {

            Console.WriteLine("y is less than or equal to z");

        }

        if (x != y && y != z && x != z)

        {

            Console.WriteLine("x,y and z are not equal with each other");

        } 

    }

}

C_Sharp_if-else_5 

There are also some logical operators which are used in “C# if else”, such as: 

  • AND(“&&”) - this returns true if both the conditions become true or get satisfied. 
  • OR(“||”) - this returns true if one of the given conditions satisfies or one of them becomes true.
  • NOT(“!”) - this returns true if the given condition is false and returns false if the given condition is true.

Short-Hand of if-else Statement

Now there’s another concept in “C# if-else” called “ternary operator,” which is mainly used for “Short-Hand of if-else Statement”.

Ternary Operators make our life very easy and help us to write the block of “C# if-else” statements in a single line by using “?:”.

If the condition becomes true, then the code will execute the next part of “?” and if it becomes false, it will execute the next part of  “:”.

The general format for writing the ternary operator statements in “C# if-else” is:

    result_variable_name = (condition) ? TrueExpression :  FalseExpression;

Example:

Now let’s take an example where we will check whether a person is an adult or not by checking his age. 

We will code this with a ternary operator; we use “?” if the condition satisfies otherwise “:”.

// C# program to demonstrate if-else statement

using System;

class practice

{

    static public void Main()

    {

               // Declaring and initializing variables

        int age = 15;

        string res;

        //shorthand if else with ternary operator

        res = age >= 18 ? "Adult" : "Not Adult";

        Console.WriteLine(res);

    }

}

C_Sharp_if-else_6 

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

In this article, we discussed “C# if-else” and saw its application. Getting a grip over this concept will help us build the logic for different types of programs as “C# if else” are the building blocks for more extensive program logic. 

Although C# is one of the popular languages, full-stack developers are the most in-demand developers currently. Due to the technical advancements and increasing skills gap, every small and large company is looking to hire a full-stack developer. You, too, can become a full-stack developer by enrolling in our Full-Stack Web Development Certification Training Course. The course offers hours of applied learning and tutorials conducted by experts across various popular programming languages and skills, such as Agile, Java, ASP.NET, AWS, JSP, Servlet, etc. Simplilearn also offers free online skill-up courses in several domains, from data science and business analytics to software development, AI, and machine learning. So why wait? Enroll today and become a certified full-stack web developer.

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.