Comparison operators

C# has a lot of operators and several of them are used to compare values. This is obviously a very common task when programming - to check how two or more values relate to each other. In this chapter, we will look into these operators used for comparing values - you probably already know some of them, but have a look anyway and see if you learn something new!

The equality operator: ==

Comparing two values can obviously be done in many ways, but to check if they are in fact equals, you can use the double-equal-sign (==) operator. Let me show you how:

int val1 = 42;
int val2 = 42;
if(val1 == val2)
        Console.WriteLine(val1 + " is equal to " + val2);

Notice how I use not one but two equal signs, right after eachother - this is important, because if you just use a single equal sign, I will be assigning a value instead of comparing it.

The NOT equal operator: !=

Sometimes you need to check if two values are non-equal instead of equal. C# has an operator for that - you just replace the first equal sign with an exclamation mark. Here's the example from before, but using the not equal operator instead:

int val1 = 42;
int val2 = 43;
if(val1 != val2)
        Console.WriteLine(val1 + " is NOT equal to " + val2);

Smaller- and bigger-than operators: < and >

Especially when comparing numbers, you will often find your self wanting to see whether one value is bigger or smaller than the other. We will use the greater-than and less-than symbols, like this:

int val1 = 42;
int val2 = 43;
if(val1 > val2)
        Console.WriteLine(val1 + " is larger than " + val2);
        if(val1 < val2)
                Console.WriteLine(val1 + " is smaller than " + val2);
                Console.WriteLine(val1 + " is equal to " + val2);