OneBite.Dev - Coding blog in a bite size

If Else Conditional Statement In C#

Code snippet for how to If Else Conditional Statement In C# with sample and detail explanation

Conditional statements in programming languages like C# allow developers to make choices depending on certain conditions. The if-else statement is one of the most commonly used conditional in C# which enables the execution of code snippets based on whether a particular condition is true or false.

Code snippet for if-else conditional statement

Below is a simple example of the use of if-else conditional statement in C#:

int temperature = 30;

if (temperature < 20)
{
    Console.WriteLine("The weather is cold");
}
else
{
    Console.WriteLine("The weather is not cold");
}

Code Explanation for if-else conditional statement

In the code snippet provided, we are trying to send a message to the console depending on the value that we are storing in the ‘temperature’ variable.

In this example, ‘temperature’ is an integer variable and its value is set to 30.

The ‘if’ keyword begins the expression of our condition. Inside the parentheses following the ‘if’ keyword, we have our condition: ‘temperature < 20’. This simply means that the code inside the ‘if’ block will only be executed if the temperature is less than 20.

Then we have Console.WriteLine(“The weather is cold”); – Console.WriteLine is a built-in C# method used to print data to the console or the output stream. If the condition that we specified (temperature < 20) evaluates to be true, then this line of code will be executed and the message ‘The weather is cold’ will be displayed.

Then we have the ‘else’ keyword. If the condition specified in the ‘if’ statement doesn’t hold true (i.e., the temperature is not less than 20), C# will ignore the ‘if’ block and execute the code inside the ‘else’ block.

Thus, in the above example since the temperature is 30, which is not less than 20, the message ‘The weather is not cold’ gets displayed.

That’s how the if-else conditional statements in C# work. They make it easy for you to control the flow of your code by making decisions based on certain conditions.

c-sharp