C# Tutorial Part 5.1 – Logical and Relational Operators

Relational Operators

Last lesson we looked at how to create a simple If Statement. They can actually get a lot more complicated than that, by using logical and relational operators. We ended the lesson by looking at how integer values could be compared, but we only used the == operator. There are in fact many other ways of comparing numerical values:

These can be used for all types of value:
== Is equal to
!= Is not equal to

These only work when comparing numerical values:
< Is less than
> Is greater than
<= Is less than or equal to
>= Is greater than or equal to

NB: You don’t have to put the < and > inequality signs twice, because they’d form another operator

Logical Operators

These allow you to join more than one condition together to make a larger condition.
If you wanted to print “Good evening, Bob!” only if it was the evening and you were talking to Bob, assuming you had a person name variable and a time of day variable, you could either write:

if(PersonName == “Bob”)
{
   if(Time == “Evening”)
   {
      Console.WriteLine(“Good evening, Bob!”);
   }
}

…which is a nested if statement – an if statement within an if statement. It is a perfectly good method but it could get messy if you have lots of them. So we have the and operator:

if((Time = “Evening”)&(PersonName = “Bob”))
{
   Console.WriteLine(“Good evening, Bob!”);
}

That is much neater and has the benefit that you can join together as many conditions as you want with a single if statement.

Here is the list of logical operators to use in your if statements:

& – And
&& – Quick And
| – Or
|| – Quick Or
^ – Exclusive Or (XOR)
! – Not

I will explain quick and, quick or and exclusive or in the next part of the tutorial, so don’t worry about those. I am ending this part here because I think a good way to learn how to use these operators is to play around with them briefly – create a few if statements of your own.
See you next time when I will fully explain each operator mentioned in this lesson!

Advertisements

About Matt

I like writing, filmmaking, programming and gaming, and prefer creating media to consuming it. On the topic of consumption, I'm also a big fan of eating.
This entry was posted in Programming and tagged , , , , . Bookmark the permalink.

Enter comment:

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s