How To Render Conditional Statements In C#

4 mins read

What is a Conditional Statement?

Conditional statements are those statements where a hypothesis is followed by a conclusion. We can also say that, a conditional statement is a feature of programming languages that tell the computer to execute certain actions, provided certain conditions are met.

Conditional statements are used through the various programming languages to instruct the computer on the decision to make when given some conditions. These decisions are made if and only if the pre-stated conditions are either true or false, depending on the functions the programmer has in mind.

All programming languages have conditional expression syntax, but some syntax are slightly different from one another. In this tutorial, we are going to use the C# Programming Language as our code sample.

C# supports the usual logical conditions from mathematics:

  • Less than x < y
  • Less than or equal to x <= y
  • Greater than x > y
  • Greater than or equal to x >= y
  • Equal to x == y
  • Not Equal to a != b

 

In C#, we can use the conditions above to perform different actions for different decisions.

Types of conditional statements in C#

  • One of the C# conditional statements is the if  statement, the if  statement specify a block of code to be executed, if a specified condition is true.

Note: the if statement must be in lowercase letter. Uppercase letters will generate an error.

Code sample

In the example below, we are going to test two values to find if 30 is greater than 10. If the condition is true, it will print “30 is greater than 10”:

 

  • Use else to specify a block of code to be executed, if the same condition is false.

Code sample

In the code sample below, we are going to create two conditions with the if  and else  statement, where if time 30 is greater than 10, so the condition is false. Because of this, we move on to the else  condition and print to the screen “Good morning”. If the time was less than 10, the program would print “Goodbye”:

  • Now let us discuss the else if, the else if statement is used to specify a new condition if the first condition is false.

Code sample:

In the example above, time (22) is greater than 10, so the first condition is false. The next condition, in the else if statement, will be true, and print to the screen “Good day”.

 

Using ternary Operator in C#

There is also a shorthand if else, which is known as the ternary operator because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements.

Code sample:

Thanks for reading…

Happy Coding!

Leave a Reply

Your email address will not be published.