Behind the Scenes Look at C#: Operators - Relational Operators
(Page 4 of 8 )
Relational operators are those operators that compare two operands and return a Boolean value indicating the relationship between them. We have six relational operators: the less than operator (<), the greater than operator (>), the greater than or equal (>=), the less than or equal (<=), the equal operator (==) and the not equal operator (!=). Don't confuse the equal operator with the assignment operator (=). In C# you can't write code like the following:
bool z = x = y;
In C++ you can, but the C# compiler will issue an error. The relational operators work exactly as you expect with the primitive types. Let's take a look at an example:
using System;
namespace Operators
{
class Class1
{
static void Main(string[] args)
{
int x = 10;
int y = 4;
bool result;
result = (x > y);
Console.WriteLine("x > y = {0}", result);
result = (x < y);
Console.WriteLine("x < y = {0}", result);
result = (x <= y);
Console.WriteLine("x <= y = {0}", result);
result = (x >= y);
Console.WriteLine("x >= y = {0}", result);
result = (x == y);
Console.WriteLine("x == y = {0}", result);
result = (x != y);
Console.WriteLine("x != y = {0}", result);
Console.ReadLine();
}
}
}
The result that will be printed to the console window is:

Exactly as we expected, x greater than y is equal to true, and so on, but what if we need to use the relational operators with objects? Let's see an example:
using System;
namespace Operators
{
class Class1
{
static void Main(string[] args)
{
Employee MichaelYoussef = new Employee();
MichaelYoussef.Age = 22;
Employee SteveAnderson = new Employee();
SteveAnderson.Age = 22;
Console.WriteLine("Michael == Steven? = {0}",
MichaelYoussef == SteveAnderson);
Console.ReadLine();
}
}
class Employee
{
public int Age;
}
}
Although both Michael and Steve are 22 years old, you will get the following result to the console window:

With objects, equality is different from value-types, because the equal operator tests the value itself when used with Value-Types. It tests for REFERENCES when used with objects. We have false in the above code because both MichaelYoussef and SteveAnderson refer to different objects on the heap, although the value of the age field is the same in both the objects. We will learn how to handle this issue in the last article of the series, titled "C# Objects Manipulation."
Next: Logical Operators >>
More C# Articles
More By Michael Youssef