Relational Operators C# with Example



Relational Operators C# with Example

Equals 
Checks whether the supplied operands (arguments) are equal 
"a" == "b" // Returns false. 
"a" == "a" //  Returns  true. 
1 == 0 //  Returns  false. 
1 == 1 // Returns true. 
false == true // Returns false. 
false == false // Returns true. 
Unlike Java, the equality comparison operator works natively with strings. 
The equality comparison operator will work with operands of differing types if an implicit cast exists from one to 
the other. If no suitable implicit cast exists, you may call an explicit cast or use a method to convert to a compatible 
type. 
1 == 1.0 // Returns true because there is an implicit cast from int to double. 
new Object() == 1.0 //  Will  not  compile. 
 

MyStruct.AsInt() == 1 // Calls AsInt() on MyStruct and compares the resulting int with 1. 
Unlike Visual Basic.NET, the equality comparison operator is not the same as the equality assignment operator. 
var x = new Object(); 
var y = new Object(); 
x == y // Returns false, the operands (objects in this case) have different references. 
x == x // Returns true, both operands have the same reference. 
Not to be confused with the assignment operator (=). 
For value types, the operator returns true if both operands are equal in value. 
For reference types, the operator returns true if both operands are equal in reference (not value). An exception is 
that string objects will be compared with value equality. 
Not Equals 
Checks whether the supplied operands are not equal. 
"a" != "b" //  Returns  true. 
"a" != "a" // Returns false. 
1 != 0 //  Returns  true. 
1 != 1 // Returns false. 
false != true // Returns true. 
false != false // Returns false. 
var x = new Object(); 
var y = new Object(); 
x != y // Returns true, the operands have different references. 
x != x // Returns false, both operands have the same reference. 
This operator effectively returns the opposite result to that of the equals (==) operator 
Greater Than 
Checks whether the first operand is greater than the second operand. 
3 > 5 //Returns false. 
//Returns true. 
1 > 0 
2 > 2 //Return false. 
var x = 10; 
var y = 15; 
x > y //Returns false. 
//Returns true. 
y > x 
Less Than 
Checks whether the first operand is less than the second operand. 
2 < 4 //Returns true. 
//Returns false. 
1 < -3 
2 < 2 //Return false. 
var x = 12; 
var y = 22; 
//Returns true. 
x < y 
//Returns false. 
y < x 
 

Greater Than Equal To 
Checks whether the first operand is greater than equal to the second operand. 
7 >= 8 //Returns false. 
//Returns true. 
0 >= 0 
Less Than Equal To 
Checks whether the first operand is less than equal to the second operand. 
2 <= 4 //Returns true. 
//Returns false. 
1 <= -3 
1 <= 1 //Returns true. 

0 Comment's

Comment Form