C# Relational Operators

C# Relational Operators are used in relational expressions which always return bool type value. To demonstrate the examples below, we'll assume we define two int variables A=15 and B=5.

OperatorUsageDescriptionExamples
==A == BReturn true if A equals B otherwise falsebool C = A == B;  //C is false because 15 does not equal to 5.
!=A != BReturn false if A equals B otherwise truebool C = A != B;  //C is true because 15 does not equal to 5.
>A > BReturn true if A is greater than B otherwise falsebool C = A > B;  //C is true because 15 is greater than 5.
<A < BReturn true if A is less than B otherwise falsebool C = A > B;  //C is false because 15 is not less than 5.
>=A >= BReturn true if A is no less than B otherwise falsebool C = A >= B;  //C is true because 15 is no less than 5.
<=A <= BReturn true if A is no greater than B otherwise falsebool C = A >= B;  //C is false because 15 is greater than 5.

>= can be translated as "greater than or equal to" and <= can be translated as "less than or equal to".

Example 01-09-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;

namespace TestRelationalOperators
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j;
            i = 9;              // 9 => i
            j = 8;              // 8 => j
            bool k = i == j;    // false => k
            Console.WriteLine("i={0}, j={1}, k={2}", i, j, k);
            Console.WriteLine("i != j: {0}", i != j);
            Console.WriteLine("i > j: {0}", i > j);
            Console.WriteLine("i < j: {0}", i < j);
            Console.WriteLine("i >= j: {0}", i >= j);
            Console.WriteLine("i <=j: {0}", i <= j);

            bool f = true;
            bool t = true;
            Console.WriteLine("f={0}, t={1}, f==t:{2}", i, j, f==t);
            Console.Read();
        }
    }
}

Output

i=9, j=8, k=False
i != j: True
i > j: True
i < j: False
i >= j: True
i <=j: False
f=9, t=8, f==t:True
  • Line 9-11: Declare 2 int variables i, j and assign values.
  • Line 12: i == j returns false and is assigned to variable k.
  • Line 13: Output i, j, k.
  • Line 14: Output the result of i != j, apparently it returns true.
  • Line 15: Output the result of i > j, apparently it returns true.
  • Line 16: Output the result of i < j, apparently it returns false.
  • Line 17: Output the result of i >= j, apparently it returns true.
  • Line 18: Output the result of i <= j, apparently it returns false.
  • Line 20-21: Declare 2 bool variables and inialize them true value.
  • Line 22: Output f==t, because they are all true, true==true returns true of course.
Please be noticed, the outputs of true or false are all capitalized the first character. That's because they all changed to string and output.