If Statements

We can now move on to actually creating logic in our applications. One very basic tool we use in our programming logic is a conditional known as the If Statement or If-Else Statement. If you remember learning about our bool data type you will recall that it has only but two values of true and false. The If Statement is a conditional that determines a Boolean value and executes or doesn’t execute based on the result. I would even argue that it makes sense even in terms of human comprehension. If x is true, do y. If x is false, don’t do y.

If you are ready then create a Visual Studio project of a console application. Preferably named, ConditionalTutorial.

 

Once your project is created, go to your Program.cs file and paste the following inside your Main method:

if(1 == 1)
{
   Console.WriteLine("Yes, 1 does equal 1");
}

if(1 != 2)
{
   Console.WriteLine("No, 1 does not equal 2");
}
Console.ReadLine();

Press F5 to run the application and as you may already have suspected, it should display the following.

C# conditional output
Console printing conditionals

 

You may have noticed I just made you do something very silly. Of course 1 equals 1 and 1 does not equal 2. Why would I make you do such a thing? Well for a couple reasons. I wanted to show you that an If Statement does not need to be provided with a bool variable. It can be given a number of operators as long as it determines a true or false result from it. I also wanted to show you the operators “==” and “!=“. These determine if the left hand and right hand values equal each other, or if the left hand and right hand values do not equal each other, respectively.

You may be asking, why do we use two equal signs and not one? The answer is that the double equal sign determines a comparison, while a single equal sign determines a declaration. For instance when we set the value of a string or an int we use a single equal sign because we are telling the compiler that x equals y. We use a double equal sign when we are telling the compiler we are asking if x equals y.

 

With this understanding, now let’s do something a little more fun. You can erase the previous code, and instead paste the following in its place:

Console.WriteLine("Enter a number between 1 and 5: ");
int myNumber = int.Parse(Console.ReadLine());
            
if(myNumber <= 5)
{
   Console.WriteLine("You entered: " + myNumber);
}
else
{
   Console.WriteLine("You didn't enter a number between 1 and 5!");
}

Console.ReadLine();

With this code we print text to the console that asks the user to enter a number between one and five. If the number is less than or equal to five we print the number that they entered. We then proceed our If Statement with and Else Statement to execute different code if the following condition was not satisfied. You’ll notice we have something new here that I have yet to mention. When we set the value of our variable myNumber we are using a method called int.Parse. This is a built in method for our int data type provided with the .NET framework. This generic essentially is passed a string value that’s converted in to an int. We also supply it with a parameter of Console.ReadLine which returns a string value of what ever the user inputted.

This code does have a few bugs. First, our If Statement only checks if the number is less than or equal to five. But the user is instructed to provide a number between one and five. With our current code if the user entered in the number zero it would be accepted as a valid input, which it is not. Second, our int.Parse method will only convert the string to an integer if it’s in an appropriate format. To put it more simply it must only contain numerical characters. If you ran the application again and instead inputted an alphabetical character such as “A” you would see the application crashes. Luckily both of these can be fixed!

Here is the code that fixes the bugs that were mentioned above:

Console.WriteLine("Enter a number between 1 and 5: ");
int myNumber = 0;
int.TryParse(Console.ReadLine(), out myNumber);
            
if(myNumber <= 5 && myNumber > 0)
{
   Console.WriteLine("You entered: " + myNumber);
}
else
{
   Console.WriteLine("You didn't enter a number between 1 and 5!");
}

Console.ReadLine();

So what do we have changed here? For one, we have extra conditions inside our If Statement with a new operator “&&“. This operator means that the statements result is only true if the conditions on the left hand and right hand side of the operator are met. It is saying if myNumber is less than or equal to five AND myNumber is greater than zero. Lastly we see we instantiated our variable myNumber to zero and then instead of int.Parse we used int.TryParse. Unlike Parse the TryParse method will process the exception thrown when it is presented with an invalid format. We also pass it not only our Console.ReadLine but our myNumber variable as well. We may also notice we use a keyword out in front of our myNumber. This is beyond the scope of this topic so that will be explained more at another time. For now you just need to know it changes the value of myNumber if the Parse is successful. If it’s not then it will stay the same, and in our case, stay at the value zero.

int.tryparse bad number
This is the console running successfully when using int.Parse

 

 

Move on to the next page >>

<< Go back to the previous page

Leave a Reply

Your email address will not be published. Required fields are marked *