#86 – Equality and Inequality Operators

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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #86 – Equality and Inequality Operators

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: