Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

How to use C# if else statements



The conditional statement if.. else in C# is using to check the conditions that we provided in the head of if statement and making a decision based on that condition. The conditional statement is examining the data using comparison operators as well as logical operators. The else statement is optional so that we can use the statement in two ways;

if (condition)
  statement;
if (condition)
  statement;
else
  statement;

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 the next level, that is if you provide else block the program will execute the code block of else statement. Otherwise, the control goes to the next line of code.

If you want to check more than one conditions at the same time, you can use else if statement.

 if (condition)
  statement;
else if (condition)
  statement;
else
  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:

  1. If the marks are greater than 80, then the student gets higher first class.
  2. If the marks are less than 80 and greater than 60, then the student gets first class.
  3. If the marks are less than 60 and greater than 40, then the student gets a second class.
  4. 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.

1:	if (totalMarks >= 80) {
2:	    MessageBox.Show("Got Higher First Class ");
3:	}
4:	else if (totalMarks >= 60) {
5:	    MessageBox.Show("Got First Class ");
6:	}
7:	else if (totalMarks >= 40){
8:	    MessageBox.Show("Just pass only");
9:	}
10:	else {
11:	    MessageBox.Show("Failed");
12:	}
  • 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 are 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 the message “Failed”.

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More