Five Minute C# — Lesson 5

Further conditional statements and their applications

Alexander Laurence
Five Minute C#
3 min readOct 28, 2018

--

Lessons: 12345678910 ・ 11 ・ 12 ・ 13 ・ 14

What if?

In our previous lesson we talked a lot about conditional statements. Now we’re about to put it to turbo-drive. Introducing the if statement.

The great thing about if statements is that they only execute the code if the given expression is true. This is very powerful, and has endless applications.

Let me show you an example!

The above code will execute the code wrapped around the curly braces {} since 2 >1 is true. But if say, 2 < 1, the console will not display the string “Worked!” because 2<1 is false. This is generally the syntax for an if statement in C#.

Of course, when we use fixed numbers like that, the statement will never change. But if statements shine when variables are used. Let me show you.

In here, only when the integer reaches greater than 3, will the console print “Hanger is full”. I hope this is starting to make sense!

Next is else statements. It compliments the if statement, and it only executes its curly braced code given that the if expression is false. Let’s have a look.

In here, it is saying print “Hanger is full!” to the console if the integer variable airplanes_in_hanger is > 3, otherwise print “There’s still space in the hanger!” if that is not true.

As you can notice, else does not depend on an expression. But if you would like it to be bound by an expression, you can use the else if statement.

We used the else if statement bound by 2 expressions using the AND operator. What we are saying with the above code is, print “Hanger is full!” to the console if the integer variable airplanes_in_hanger is > 3, otherwise if the airplanes_in_hanger variable is more than 2 and less than 3, print “Hanger nearing full capacity!”.

Pretty cool right? Now we are beginning to look like programmers! I hope you can see the sheer potential that if, else, and else if statements can have in building solutions to real world problems.

I want you to now write your own program using everything you know from lesson 1 to 5. You can make it about almost anything. Post your code in the comments below!

--

--

Alexander Laurence
Five Minute C#

Alex graduated from the University of Edinburgh with a Masters degree in Neuroscience. He spent 3 years teaching and now runs his own tech venture.