Search results
In this article, I am going to discuss If-Else Statements in C# with Examples. Please read our previous article, where we discussed Control Flow Statements in C# with Examples. The If-Else Statements belong to the Selection Statements or Branching Statements Category.
C# if...else if (if-then-else if) Statement. When we have only one condition to test, if-then and if-then-else statement works fine. But what if we have a multiple condition to test and execute one of the many block of code. For such case, we can use if..else if statement in C#. The syntax for if...else if statement is:
C# has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
C# - if, else if, else Statements. C# provides many decision-making statements that help the flow of the C# program based on certain logical conditions. Here, you will learn about if, else if, else, and nested if else statements to control the flow based on the conditions.
In this tutorial, you'll learn how to use the C# if else if statement to check multiple conditions and execute a block if a condition is true.
1) Simple C# if else statement examples. The following example uses the if else statement to show a message when the condition is "sunny": string condition = "sunny"; if (condition == "sunny") { Console.WriteLine("Let's go outside."); } else { Console.WriteLine("Just stay home."); } Code language: C# (cs) Output: Let 's go outside. Code ...
Branching with if and else in C# is straightforward. using System; class Program { static void Main() { // Here's a basic example. if (7 % 2 == 0) { Console.WriteLine("7 is even"); } else { Console.WriteLine("7 is odd"); } // You can have an if statement without an else.