Whenever we have certain conditions that are circling base on specific decision then we used the if-else statement. In if-else we check either a specific condition is true or false if condition is true then that true condition will execute otherwise false condition in else part will execute, so we can do this type of decision making base on certain condition in if-else statement.
Here, in below example
int applePrice = 60; - We have declared and initialized a local varaible with named int price = 60. We will use this price variable to test boolean expression in if-else-condition.
if (price == 50) - we have if (price == 50) a boolean expression which will be true or false. It will test if price is equal 50 then will return true otherwise return false.
Console.WriteLine("Apple price is equal to 50."); - When If-else condition will be true then block of statement will execute and it will print "Apple price is equal to 50."
Console.WriteLine("Apple price is not equal to 50."); - When If-else condition will be false then else block of statement will execute and it will print "Apple price is not equal to 50.".
We have defined a if else statement that checks a condition is true or false. If it is true then 1st body of condition will execute. If it is fasle then 2nd body will execute.
We choose if else statement due to the following reasons.
Binary Choice:
Whenever you have this type situation in which you have a binary choice where you want to execute one block of code if a condition is true and another block if it is false, an if-else statement is a natural choice. If you are using two if statement to make some binary choice, concisely you can use if-else statement for the same purpose.
Mutually Exclusive Conditions:
If you have mutually exclusive conditions, meaning that only one condition among several can be true, an if-else construct is a suitable choice. It ensures that only one block of code is executed, even if multiple conditions are true.
Fallback or Default Case:
When you want to provide a default action or fallback behavior when none of the conditions are true, if-else can be used for the final else block. This is helpful for error handling or handling unexpected cases.
Whenever you have multiple conditions base on some specific binary decisions then if-else is best choice rather using if condition multiple time.