In C#, the equality and inequality operators are used to check the equivalence of two operands. The operands can be of any type.
- == Equality
- != Inequality
These operators always take two operands and return a boolean value.
- == Returns true if its operands are equal
- != Returns true if its operands are not equal
The behavior of the operators depends on the type:
- Value types – equal if values are equal
- Reference types – equal if the operands point to the same object
- string type – equal if the values are equal
- Custom types – you can override the behavior
Examples:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| // Value types bool b1 = (1 == 2); // false int i = 12, j = 12; b1 = (i == j); // true b1 = (i != j); // false // Reference types Cat c1 = new Cat( "Herman" ); Cat c2 = new Cat( "Boris" ); Cat c3 = new Cat( "Herman" ); Cat c4 = c1; b1 = (c1 == c2); // false b1 = (c1 == c3); // false, though same name b1 = (c4 == c1); // true, both point to the same Cat |