Hey there, Gamers and game Makers!
In this week's blog post, we will continue our introduction to C# in Visual Studio series by looking at if statements. We use if statements when we want to check if certain conditions have been met before executing a particular body of code. For this example, we're going to create a console app that asks the user to input their age. If they are over 18, we tell them so. If they are under 18, we will tell them something to that effect.
As you can probably guess based on the first tutorial on variables, we are going to need an int variable to store the age. We'll create an int variable called age but we wont assign it any value at this time. We will then use a Console.ReadLine() to assign the users input from the keyboard to be the value of age.
We can now write our If Statement. An if statement consists simply of writing if followed by the conditional expression you are checking in brackets. This is then followed by the code you wish to execute if the condition is met in curly brackets. In this example we are checking if the age value is greater or equal to 18, we will display to the screen a message saying you are old enough to enter. With if statements we can also have else ifs that will check another condition should the first one fail. You can do as many of these as you wish but one would urge not overdoing it as it can create messy code.
I have a single else if that checks if the age value is less than 18 should the first if fail to find the value to be above 18. if it is below 18, we display a message to the screen saying you are old enough to enter. We can also have else statements. These do not check a condition but rather execute a body of code should all previous ifs fail. This can be useful should the user enter an incorrect value and we need to notify them of such. Our program looks as follows.
If statements can be used to check conditional expressions on strings, bools and more. The logic is the same. We can also use the "or" operator, || and the "And" operator, && to check multiple conditions at once before executing a body of code. With the && operator, both conditions must be met in order for the code to execute. However, with the || operator, only one of the conditions has to be true. For example.
In the next tutorial in this series, we'll be looking at how to use loops.
Until next time!