How to use C# if else statements
The conditional statement if.. else in C# is using for check the conditions that we provided in the head of if statement and making decision based on that condition. The conditional statement examining the data using comparison operators as well as logical operators. The else statement is optional , so we can use the statement in two ways ;
If the condition is true then the control goes to the body of if block , that is the program will execute the code inside if block.
If the condition is false then the control goes to next level , that is if you provide else block the program will execute the code block of else statement, otherwise the control goes to next line of code.
If you want to check more than one conditions at the same time , you can use else if statement .
Just take a real-time example - We have a mark list and we want to analyze the grading of each student. In this case we can use if..else conational statements.
Following are the grading rule of the student:
- If the marks is greater than 80 then the student get higher first class.
- If the marks less than 80 and greater than 60 then the student get first class.
- If the marks less than 60 and greater than 40 then the student get second class.
- If all the above conditions failed and the marks less than 40 then the student is failed.
Now here implementing these conditions in a C# program.
- Line 1 : Checking the total marks greater than or equal to 80.
- Line 2 : If total marks greater than 80 show message - "Got Higher First Class ".
- Line 4 : Checking the total marks greater than or equal to 60 .
- Line 5 : If total marks greater than 60 show message - "Got First Class ".
- Line 7 : Checking the total marks greater than or equal to 40.
- Line 8 : If total marks greater than 40 show message - "Just pass only".
- Line 10: If those three conditions failed program go to the next coding block .
- Line 11: If all fails, it will show message "Failed".
In this C# example the total marks is 59 , when you execute this program you will get in message box "Just Pass Only"