#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers