Reflection

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:

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:

Smaller/bigger than or equal to: <= and >=

In the above example, we check if a value is smaller or bigger than another, but sometimes, instead of just smaller/bigger, you want to see if something is smaller-than-or-equal-to or bigger-than-or-equal-to. In that case, just put an equal sign after the smaller/bigger-than operator, like this:

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

Summary

Comparing stuff is such an essential task in programming, but fortunately, C# has a wide selection of operators to help you, as shown in this article. However, sometimes comparing two objects are not as simple as comparing two numbers - for that, C# allows you to write your own, custom methods for doing stuff like comparison. We will look into that in the article about operator overloading.