C# – if Statement
In C#, if statement is used to indicate which statement will execute according to the value of the given boolean expression. When the value of the boolean expression is true, then the if statement will execute the given then statement, otherwise it will return the control to the next statement after the if statement.
- In C#, you are allowed to use if statement with then statement or with else statement according to your requirement.
- Then statement contains single or multiple statements and these statements are enclosed in curly braces({}). For a single statement, braces can be optional, if the curly brackets {} are not used with if statements, then the statement just next to it is only considered associated with the if statement.
- Then statement can be of any kind/type like it may contain another if-else statement.
Syntax:
if(condition) { then statement; }
Flow Chart:
Let us discuss if statements with the help of the given examples:
Example 1:
C#
// C# program to demonstrate // if statement using System; class GFG{ static public void Main() { // Declaring and initializing variables string x = "w3wiki" ; string y = "w3wiki" ; // If statement if (x == y) { Console.WriteLine( "Both strings are equal..!!" ); } // If statement if (x != y) { Console.WriteLine( "Both strings are not equal..!!" ); } } } |
Output:
Both strings are equal..!!
Explanation: In the above example, we have two strings, i.e., x and y. Now in the first, if statement, we compare string x to string y and the result of the comparison is true. So, the then block executes and prints “Both strings are equal..!! “. Now in the second if statement, we check both strings are not equal, but the strings are equal, so the then block of this if statement will not execute.
Example 2:
C#
// C# program to demonstrate nested // if statement using System; class GFG{ static public void Main() { // Declaring and initializing variables string emp_name = "Rohit" ; int salary = 10000; // If statement // Here if condition checks // the employee name is equal to rohit if (emp_name == "Rohit" ) { // Nested if statement // Here if the salary of Rohit // is greater than 50000 then // he is eligible to pay tax // Otherwise not eligible if (salary > 50000) { Console.WriteLine( "Eligible to pay tax" ); } else { Console.WriteLine( "Not Eligible" ); } } } } |
Output:
Not Eligible
Example 3:
C#
// C# program to illustrate if statement // Using AND, OR, NOT operators using System; class GFG{ static public void Main() { // Declaring and initializing variables int x1 = 15; int x2 = 18; int x3 = 20; // If statement // Using AND operator if (x1 > 20 && x2 > 20) { Console.WriteLine( "Enter group A" ); } // If statement // Using OR operator if (x1 < 30 || x3 == 20) { Console.WriteLine( "Enter group B" ); } // If statement // Using NOT operator if (!(x1 > 20 && x2 > 20)) { Console.WriteLine( "Enter group C" ); } } } |
Output:
Enter group B Enter group C
Contact Us