C# – if Statement
Last Updated :
12 Sep, 2022
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#
using System;
class GFG{
static public void Main()
{
string x = "GeeksforGeeks" ;
string y = "GeeksforGeeks" ;
if (x == y)
{
Console.WriteLine( "Both strings are equal..!!" );
}
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#
using System;
class GFG{
static public void Main()
{
string emp_name = "Rohit" ;
int salary = 10000;
if (emp_name == "Rohit" )
{
if (salary > 50000)
{
Console.WriteLine( "Eligible to pay tax" );
}
else
{
Console.WriteLine( "Not Eligible" );
}
}
}
}
|
Output:
Not Eligible
Example 3:
C#
using System;
class GFG{
static public void Main()
{
int x1 = 15;
int x2 = 18;
int x3 = 20;
if (x1 > 20 && x2 > 20)
{
Console.WriteLine( "Enter group A" );
}
if (x1 < 30 || x3 == 20)
{
Console.WriteLine( "Enter group B" );
}
if (!(x1 > 20 && x2 > 20))
{
Console.WriteLine( "Enter group C" );
}
}
}
|
Output:
Enter group B
Enter group C
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...