Testing a condition is inevitable in programming. We will often face situations where we need to test conditions (whether it is true or false) to control the flow of the program. These conditions may be affected by the user's input, the time factor, the current environment where the program is running, etc.
In C# program execution flow control by the statement of control. If...else
condition program first checks the condition if the condition true, then the compiler will execute the block code otherwise it will move toward the else statement.
An if statement identifies which statement to run based on the value of a Boolean expression. In the following example, the bool variable condition is set to true and then checked in the if statement. The output is that the variable is about to true.
if (boolean - expression)
{
// statements executed if boolean-expression is true
}
The boolean-expression will return either true or false.
bool condition = true;
if (condition)
{
Console.WriteLine("true.");
}
true.
See another example with an integer type variable
int number = 10;
if (number== 10)
{
Console.WriteLine("you are in if statement");
}
you are in if statement
The if statement in C# may have an optional else statement. The block of code inside the else statement will be executed if the expression is evaluated to false.
if (boolean - expression)
{
// statements executed if boolean-expression is true
}
else
{
// statements executed if boolean-expression is false
}
The fоrmаt оf the if-else struсture соnsists оf the reserved wоrd if, Bооleаn exрressiоn, bоdy оf а соnditiоnаl stаtement, reserved wоrd else аnd else-bоdy stаtement. The bоdy оf else-struсture mаy соnsist оf оne оr mоre орerаtоrs, enсlоsed in сurly brасkets, sаme аs the bоdy оf а соnditiоnаl stаtement.
int condition = 100;
if (condition == 10)
{
Console.WriteLine("you are in if statement");
}
else if (condition == 15)
{
Console.WriteLine("you are else if statement");
}
else
{
Console.WriteLine("you are in else statement");
}
you are in else statement
Sometimes the рrоgrаmming logic in а рrоgrаmming or an аррliсаtiоn needs to be represented by multiple if-structures соntаined in eасh оther. We саll them nested if or nested if-else structures.
int condition = 100;
if (condition == 100)
{
if (condition > 100)
{
Console.WriteLine("you are in if statement");
}
else
{
Console.WriteLine("you are in else statement");
}
}
else if (condition == 15)
{
Console.WriteLine("you are else if statement");
}
else
{
Console.WriteLine("you are in else1 statement");
}
you are in else statement
The ternary operator is also known as a short hand if-else statement
using System;
namespace EntryPoint
{
class Program
{
//Ternary operator
static unsafe void Main(string[] args)
{
int number = 100;
string result = (number < 90) ? "if statement" : "else statement";
Console.WriteLine(result);
}
}
}
else statement