# #86 – Equality and Inequality Operators

September 11, 2010 1 Comment

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:

// 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

Advertisements

Pingback: #396 – Operators as Class Members « 2,000 Things You Should Know About C#