Intro to decisions with if clauses
In this article, you will get a brief introduction to decisions in CSharp. It is extremely important in programming to execute certain code only when a certain condition is met. Let’s look at an example from real life. Let’s assume, we want to go out in the evening and do not want to take more money with us than required. Then we stand before the cash machine and must make a decision. How much money do we take with us ?!
Example decisions in CSharp
Option1: If we want to go to the cinema, we only withdraw 30 €. This pays for the train ticket, the cinema ticket and the popcorn.
Option2: If we go to a concert, then we withdraw 100 €, so the ride and the ticket are paid.
Option 3: We stand in front of it and decide to stay at home. So we withdraw 15 € to order something from the delivery service. So you see, we have different conditions here, which all results in different results. If you want to write this in a program, then you use If statements. Thus, if a particular situation is met, a particular action is performed. Naturally, there are, of course, much more complex decision-making possibilities which could be solved programmatically.
Example for If statements in CSharp
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Panjutorials { class Program { static void Main(string[] args) { string goOut= ""; if(goOut== "cinema") { Console.WriteLine("Withdraw 30€"); } if(goOut== "concert") { Console.WriteLine("Withdraw 100€"); } if(goOut== "") { Console.WriteLine("Withdraw 15€"); } Console.Read(); } } }
So now we ask with “if” and the actual condition within the brackets and the double equal sign if our variable is either cinema, concert or empty. In case it is empty we don’t go out but still need money to pay for the ordered food.
Now you see how you can use the if statement. We are going to work with if statements a lot more. Also we are going to use much more complex examples including relative and logical operators (more on that later).