    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Some Objects Are More Equal Than Others</title>
        <link>https://members.accu.org/index.php/journals/1971</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #103 - June 2011 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c297/">o103</a>
                    (7)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c297-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c297+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Some Objects Are More Equal Than Others</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 06 June 2011 20:23:42 +01:00 or Mon, 06 June 2011 20:23:42 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Comparing objects is a fundamental operation. Steve Love and Roger Orr consider different language approaches.</p>
<p><strong>Body:</strong>&nbsp;<p>Testing for equality is an important concern in a lot of programming tasks and is often used for control flow: equality is one of the commonest expressions used in <code>if</code>, <code>for</code> and <code>while</code> statements. However despite being something that is covered in almost any introduction to a programming language the concept and implementation of equality can be quite complicated.</p>

<h2>Possible meanings of â€˜equalityâ€™</h2>

<p>There are a wide variety of meanings to the use of â€˜equalityâ€™ in a programming language. The list of possible meanings includes:</p>

<ol>
	<li>Refer to the same memory location</li>
	<li>Have the same value</li>
	<li>Behave the same way</li>
</ol>

<p>This article explores some of the details and pitfalls with equality in terms of just the first two items on this list. We found it was a harder task than it appears at first glance to get it right (for some definition of right), even ignoring the third item on our list or looking further afield for other meanings.</p>

<p>The first item in the list is often described as â€˜identity comparisonâ€™ and the second one as â€˜value comparisonâ€™, and we make use of these terms below. Note that value comparison usually refers to the <em>perceived</em> value for users of the object and fields that donâ€™t affect this (for example internally cached values) are usually not included in the comparison code.</p>

<p>We are further restricting the subject to focus primarily on only three languages: C++, C# and Java. Despite their common heritage and obvious similarities there are many differences in the sort of problems equality raises in each language: even at the basic level of language syntax we see:</p>

<ul>
	<li>In Java: <code>a == b</code> always does something for all variables <code>a</code> and <code>b</code> of the same type (and compiles in some cases when they are of different types) and you cannot change what it does.</li>
	
	<li>In Java &amp; C#: <code>anobject.[eE]quals(another)</code> always does something (we write <code>[eE]quals</code> because the method is spelled <code>equals</code> in Java but <code>Equals</code> in C#)</li>
	
	<li>In C++ &amp; C# you can overload the meaning of <code>==</code> and in C# &amp; Java you can override <code>[eE]quals</code> to customize behaviour.</li>
</ul>

<p>Letâ€™s start with the language construct form of equality â€˜<code>==</code>â€™ on the grounds that this must be a pretty fundamental definition to have been enshrined in the syntax of the programming language, What does each language provide for this operator â€˜out of the boxâ€™?</p>

<p>In C++ â€˜<code>==</code>â€™ is predefined (as a value comparison) for all built-ins and the subset of the library types for which equality makes sense (e.g. <code>std::string</code>), but is not automatically provided for custom types defined in a program. However you can provide your own definitions of <code>operator== </code>as long as at least one argument is a custom type: and you can also specify your own return type for the operator (although returning anything but <code>bool</code> is usually a bad decision.)</p>

<p>In Java â€˜<code>==</code>â€™ is predefined for primitive built-ins and does a straightforward value comparison. For object types â€˜<code>==</code>â€™ performs identity comparison between the two objects supplied. You cannot change this behaviour.</p>

<p>In C# â€˜<code>==</code>â€™ is predefined, or overridden, for all built-ins and library types (whether these types are <em>reference</em> [<code>class</code>] or <em>value</em> [<code>struct</code>] types). It is not automatically provided for custom value types and performs identity comparison for custom reference types. C# lets you define â€˜<code>==</code>â€™ for any custom type, but you must additionally provide an implementation of â€˜<code>!=</code>â€™.</p>

<h2>Object comparisons</h2>

<p>For Java and C# the presence of a single root class for all object types allows for a sensible definition of an equality method in this base class which takes an argument of the base class. In both languages the default implementation of this method, on custom types, performs identity comparison.</p>

<p>Java overrides <code>equals()</code> for some of the predefined types, such as <code>Integer</code>. However there is some confusing behaviour as Listing 1 demonstrates.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public class IntegerEquals
{
  public static void main(String[] args)
  {
    test(10);
    test(1000);
  }
  public static void test(int value)
  {
    System.out.println(&quot;Testing &quot; + value);
    Object obj = value;
    Object obj2 = value;
    if (obj.equals(obj2))
       System.out.println(&quot;Equals&quot;);
    if (obj == obj2)
      System.out.println (&quot;==&quot;);
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>If you compile and run this simple program you might be surprised:</p>

<pre class="programlisting">
  Testing 10
  Equals
  ==
  Testing 1000
  Equals</pre>

<p>The two objects <code>obj</code> and <code>obj2</code> compare the same using the <code>equals</code> method (as the overridden method in Integer compares values not identity) when executed with <code>value</code> set to 10 or 1000 as expected. However, on most implementations of Java, <code>obj</code> compares the <strong>same</strong> as <code>obj2</code> using <code>==</code> when value is set to 10 but they compare <strong>different</strong> when the value is set to 1000. What is happening here?</p>

<p>This is a consequence of an optimisation in the Java code that boxes primitive data into Integer objects. The compiler implements <code>obj == value</code> by calling <code>Integer.valueOf(value)</code> and this method caches â€˜commonly used valuesâ€™ such as 10<a href="#FN01"><sup>1</sup></a>. Hence in the first case the compiler is performing identity comparison on two references to the same, cached, <code>Integer</code> with value 10 and in the second case the compiler is performing identity comparison on references to two <em>separate</em> temporary <code>Integer</code> objects with value 1000.</p>

<p>There is a similar problem with internâ€™ed strings (strings held in a shared pool of unique strings normally accessed using the <code>String.intern()</code> method) as demonstrated in Listing 2.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public class Intern
{
  private static final String s1 = &quot;Something&quot;;
  private static final String s2 = &quot;Some&quot;;
  private static final String s3 = &quot;thing&quot;;
  public static void main( String [ ] args )
  {
    if (s1 == s2 + s3)
       System.out.println(&quot;match!&quot;);
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>This program prints <code>match!</code> when executed as the compiler ensures that strings with the same compile time value generate references to a single object. This is perfectly safe since strings in Java are immutable, but can cause some confusion. In general checking strings for equality in Java with <code>==</code> is unsafe and some tools provide a warning for attempts to do so. The danger is that compile time strings, which are interned, are treated differently from any runtime strings (which typically arenâ€™t).</p>

<p>The classic case where this causes problems is that unit tests, which typically use compile time strings, will pass most tests successfully whether you use the <code>equals</code> method or the <code>==</code> operator; but in actual use with runtime generated strings (such as those read from a file) the behaviour is different.</p>

<p>C# implicitly provides some implementation assistance with the <code>Equals</code> method for value types, but itâ€™s more complicated than it might appear at first sight. (Listing 3)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
struct Easy
{
  int X;
  int Y[ 100 ] ;
}

struct Hard
{
  int X;
  MyType Y;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>Both these structures will have an <code>Equals</code> method synthesised by the compiler. The first class (<code>Easy</code>) only contains basic scalar members and the <code>Equals</code> method will perform a bit-wise check on the two values (using the total size of the object), which is often exactly the desired behaviour (and is fast). In the case of the second class (<code>Hard</code>) the presence of the custom type <code>MyType</code> means that the synthesised <code>Equals</code> method performs reflection on the class at run time to identify the fields and then does a member-wise comparison of all the members (including the basic scalar <code>int</code> member <code>X</code>). While this produces the correct answer the performance is likely to be significantly worse than an explicit implementation of equality.</p>

<p>Finally in both C# and Java thought needs to be given to ensure the primary object reference is non-null. The simple example in Listing 4 demonstrates the problem and also a way (in C# only) to avoid it.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public class NullEquals
{
  public static void Main()
  {
    object a = null;
    object b = new object();
    if (a.Equals( b ))
      Console.WriteLine(&quot;Now there's a thing&quot;);
    if (object.Equals(a, b))
      Console.WriteLine(
      &quot;This should be safe enough&quot;);
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<p>This program fails with a <code>NullReferenceException</code> as <code>a</code> is null in the first call to <code>Equals</code> and you cannot call a method on a <code>null</code> object. The second call, using the static method taking two arguments. does not throw such an exception when supplied with null references (and returns <code>false</code> if either <code>a</code> or <code>b</code> is <code>null</code> and <code>true</code> if they both are).</p>

<p>C++ does not have a single object root and so it doesnâ€™t really make sense to have an equals method, but it <strong>does</strong> have templates and to help with programming the STL there is <code>std::equal_to</code>, which by default performs <code>==</code>. You can specialise it for your own type to pass your own types to methods and classes implemented in terms of <code>equal_to</code> such as <code>std::unordered_map</code> (see Listing 5 for an example).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
#include &lt;functional&gt;
#include &lt;iostream&gt;
int main( )
{
  std::cout &lt;&lt; &quot;std::equal_to&lt;int&gt;()(10,10): &quot;
    &lt;&lt; std::equal_to&lt;int&gt;()(10,10) &lt;&lt; std::endl;
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<p>The full story for C# is even more complex as there is a long list of equality measures, which have been added to as various new versions of the .Net framework have been released. The list includes:</p>

<ul>
	<li><code>object.Equals</code> (weâ€™ve already seen both flavours of this one)</li>
	<li><code>object.ReferenceEquals</code></li>
	<li><code>IEquatable&lt;T&gt;</code></li>
	<li><code>IEqualityComparer</code></li>
	<li><code>IEqualityComparer&lt;T&gt;</code></li>
	<li><code>EqualityComparer&lt;T&gt;</code></li>
	<li><code>IStructuralEquatable</code></li>
	<li><code>StringComparer</code></li>
</ul>

<p>...and others weâ€™ve probably missed...</p>

<p>The second element of this list, the <code>ReferenceEquals</code> method, is used to perform the identity check: that two references refer to the same object. The method is needed because <code>==</code>, which performs this check by default, can be overridden. (Since Java does not allow operator overloading it has no need for such a method.)</p>

<p>However, when used in conjunction with object boxing, <code>object.ReferenceEquals</code> has some interesting behaviour (see Listing 6).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public class RefEqual
{
  public static void Main()
  {
    int ten = 10;
    System.Console.WriteLine(
       object.ReferenceEquals(ten, ten));
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 6</td>
	</tr>
</table>

<p>This program prints <code>False</code> because the two temporary boxed integer objects created to pass into the <code>ReferenceEquals</code> method are distinct, and hence different, objects. This is a related problem to the one shown above using the Java <code>Integer</code> class.</p>

<h2>Overloading equality</h2>

<p>Both Java and C# allow the programmer the freedom to overload the <code>[eE]quals</code> method to take an argument of a different type. Listing 7 is an example in Java that shows the problems of a naive implementation.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public class OverloadingEquals
{
  private int value;

  public OverloadingEquals(int initValue)
  {
    value = initValue;
  }

  public boolean equals(OverloadingEquals oe)
  {
    return oe != null &amp;&amp; oe.value == value;
  }

  public static void main(String[] args)
  {
    OverloadingEquals oe1 
       = new OverloadingEquals(10);
    OverloadingEquals oe2 
       = new OverloadingEquals(10);
    Object obj1 = oe1;
    Object obj2 = oe2;
    System.out.println(&quot;oe1.equals(oe2): &quot;
       + oe1.equals(oe2));
    System.out.println(&quot;oe1.equals(obj2): &quot; 
       + oe1.equals(obj2));
    System.out.println(&quot;obj1.equals(oe2): &quot; 
       + obj1.equals(oe2));
    System.out.println(&quot;obj1.equals(obj2): &quot; 
       + obj1.equals(obj2));
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 7</td>
	</tr>
</table>
 
<p>This program prints:</p>

<pre class="programlisting">
  oe1.equals(oe2): true
  oe1.equals(obj2): false
  obj1.equals(oe2): false
  obj1.equals(obj2): false</pre>

<p>even though the <strong>same</strong> objects are being compared in each case. The trouble is that the overloaded method is called based on the <strong>compile</strong> time type of both the primary object and the argument. What you probably want in this case is logic based on the <code>runtime</code> type.</p>

<p>There are some principles from the mathematics of â€˜equivalence relationsâ€™that, if adhered to, result in a consistent use of the concept of equality. They are that equality is...</p>

<ul>
	<li><strong>Reflexive</strong>
		<p>a==a is always true</p>
	</li>
	
	<li><strong>Commutative</strong>
		<p>if a==b then b==a</p>
	</li>
	
	<li><strong>Transitive</strong>
		<p>if a==b and b==c then a==c</p>
	</li>
	
	<li><strong>Reliable</strong>
		<p>Never throws. (This means checking for null!)</p>
	</li>
</ul>

<p>These rules are listed out in fuller detail in the language references for both C# [<a href="Love-Orr.xml#id(C# Equals)">C# </a>Equals] and Java [<a href="Love-Orr.xml#id(Java Equals)">Java </a>equals]. The wording from the C++ standard is short enough to quote in full: â€˜<em>(5.10p4) Each of the operators shall yield true if the specified relationship is true and false if it is false.</em>â€™ There you have it: succinct at any rate!</p>

<p>Now let us try and apply these rules when considering polymorphic equality. Consider a two-dimensional coordinate class in C# (Listing 8).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
class Coordinate
{
  public double X { get; set; }
  public double Y { get; set; }
  public override int GetHashCode()
  {
    // ... 
  }
  public override bool Equals(object other)
  {
    var right = other as Coordinate;
    if (right != null)
      return X == right.X &amp;&amp; Y == right.Y;
    return false;
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 8</td>
	</tr>
</table>

<p>We might extend this class to support a three-dimensional coordinate system (Listing 9).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
class Coordinate3d : Coordinate
{
  public double Z { get; set; }
  public override int GetHashCode()
  {
    // ...
  }
  public override bool Equals(object other)
  {
    var right = other as Coordinate3d;
    if (right != null)
      return base.Equals( other ) &amp;&amp;
        Z == right.Z;
    return false ;
  }
}

			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 9</td>
	</tr>
</table>

<p>How does this polymorphic equality fare when checked against our four relationships for equality?</p>

<pre class="programlisting">
  var p1 = new Coordinate { X = 2.3, Y = 5.6 };
  var p2 = new Coordinate3d { X = 2.3, Y = 5.6,
                              Z = 10.11 };
							  
  p1.Equals( p2 ) is True
  p2.Equals( p1 ) is False</pre>

<p>Oops. The equality relationship fails the <strong>commutative</strong> requirement. We can improve our conformance to this requirement in C# by implementing <code>IEquatable&lt;T&gt;</code> â€“ which enforces implementation of an override of <code>Equals</code> taking <code>T</code> â€“ for both classes. This provides the symmetry for <code>p1</code> and <code>p2</code> but is still not a complete solution to the problem as this code fragment shows:</p>

<pre class="programlisting">
  object o1 = p1;
  Console.WriteLine(
     &quot;p1.Equals(o2) {0}, o2.Equals(p1) {1}&quot;,
     p1.Equals(o2), o2.Equals(p1));</pre>
	 
<p>However, even if we fix the commutative relation by making our equality test more complex we <em>still</em> have a problem. Letâ€™s add this variable:</p>

<pre class="programlisting">
  var p3 = new Coordinate3d {
     X = 2.3, Y = 5.6, Z = 1.22 };</pre>

<p>Now <code>p1</code> will be equal to <code>p3</code> (for the same reason it is equal to <code>p2</code>), but <code>p2</code> and <code>p3</code> will <em>not</em> compare equal. We have broken the <strong>transitivity</strong> requirement. How can we resolve this? Should we even try?</p>

<p>Letâ€™s consider <em>why</em> we have the problems we see. Our problems are mostly caused by attempting to define equality in a class hierarchy. What sense is there to try and compare a two-dimensional and three-dimensional object? They are not the same class. The first solution is to change our design so that two and three dimensional classes are not related: we might use composition in preference to inheritance if we do wish to use some of the implementation of <code>Coordinate2d</code> in the implementation of <code>Coordinate3d</code>.</p>

<p>When inheritance is needed a good solution to the problematic elements of value equality is to allow comparison to succeed only if the actual run-time class types are the same, which can be implemented simply enough in C# by comparing the results of calling <code>GetType()</code> on each object.</p>

<h2>Incidental and intentional equality</h2>

<p>Avoid defining equality just so it can be used in conjunction with something that requires it, e.g. hashed containers. While it may make the initial implementation simpler to define â€˜just enoughâ€™ equality to be able to use the type in this way, such partial implementations of equality have a nasty habit of causing more serious problems later on as the code evolves.</p>

<p>Suppose for example that you have a C# class and wish to create a <code>HashSet</code> of objects from this class. It can be tempting to define an <code>equals()</code> method on the class that fulfils just the checks necessary for this usage. However the equality used for a comparison in this context might be very different from one used elsewhere: perhaps only certain key fields are relevant. In this case an alternative way of solving the problem exists as the C# <code>HashSet</code> can use a pluggable equality comparer (<code>IEqualityComparer&lt;T&gt;</code>) instead of using <code>equals()</code>. This also provides a clearer way of stating the intent than implementing the equality operator just for using in the hash set. In C++ the <code>unordered_set</code> can be given its own equality comparer; however in the standard Java collection classes <code>HashSet</code> can only use <code>object.equals()</code>, so youâ€™re stuck with it. </p>

<p>Within a single application, <em>both</em> meanings of equality might be required: for example in an application for playing card games do you need <strong>the</strong> Ace of Spaces or <strong>an</strong> Ace of Spades? In Java and C#, override <code>[Ee]quals</code> for a value-check and leave <code>==</code> well alone to perform its default action of an identity check. In C++, which allows access to the address of an object, you can explicitly compare addresses (for identity) or contents (for value). Unless of course someone has defined <code>operator&amp;</code> for one of the types...</p>

<h2>Hashcodes</h2>

<p>There is a close relationship between equality and hashing. For example the C# documentation states that â€˜<em>classes [..] must [...] guarantee that two objects considered equal have the same hash code</em>â€™. Java imposes a similar rule for <code>Object.hashCode()</code>.</p>

<p>The reason is simple: when hashing functions are used with collections of objects the hash code is used first as a coarse filter to partition objects into buckets with the same, or related, hash codes. If you implement a hash code function that means two objects comparing equal have a different hash code then the two objects may end up in different buckets and the code wonâ€™t ever get to the point of testing for equality.</p>

<p>Hash codes for objects that can mutate are another problem. See Listing 10 for an example.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
public static class Bogus
{
  public String Value;
  @Override public int hashCode()
  {
    return Value.hashCode();
  }
  @Override public boolean equals( Object other )
  {
    return ((Bogus)other).Value.equals( Value );
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 10</td>
	</tr>
</table>

<p>Consider what happens if <code>Value</code> changes after inserting into a hashed container... if the objectâ€™s hash code changes after being added to a hashed container, subsequent attempts to look for the object in the container will be accessing the wrong bucket.</p>

<p>The default implementation of <code>GetHashCode()</code> in C# for a value type is the hash code of the first field â€“ this is rarely the best implementation for most value types. While we were investigating hash code behaviour in C# we found an interesting â€˜featureâ€™ of the Microsoft C# runtime: the hash code for a <code>boolean</code> value is constant! The program in Listing 11 demonstrates both these behaviours by printing <code>True</code> both times when compiled and run using Microsoftâ€™s implementation.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
using System;
static class Program
{
  struct HashTest
  {
    public bool Enabled;
    public string Value;
  }

  public static void Main()
  {
    var h1 = new HashTest{
       Enabled = true, Value = &quot;Great!&quot;};
    var h2 = new HashTest{
       Enabled = false , Value = &quot;Great!&quot;};
    Console.WriteLine(
       h1.GetHashCode() == h2.GetHashCode());
    h1.Value = &quot;Rubbish!&quot;;
    Console.WriteLine(
       h1.GetHashCode() == h2.GetHashCode());
  }
}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 11</td>
	</tr>
</table>

<p>Using Visual Studio this program prints:</p>

<pre class="programlisting">
  True
  True</pre>

<h2>Collections</h2>

<p>Another set of issues is raised by considering equality on container types. When are two collections of things equal? Is it enough that the two containers have the same items or do they need to be in the same order? (As a side note, we can add to the C# list of equality checks with <code>SequenceEqual</code>, which insists on the same items, in the same order).</p>

<p>This is a question that has performance implications too: comparing two sets are equal when permutations are allowed has a higher complexity measure than the case when the ordering must match.</p>

<p>A further question that may need addressing with containers is whether you want a value or reference comparison: do two containers match if they contain the identical objects or if they contain objects with identical values?</p>

<p>Note that this is a case where polymorphic equality makes a lot of sense: two collections are equal when they contain the same objects. You are not usually interested in whether they are from the same class (or even whether the internal states are the same); the important thing for equality is the objects they contain.</p>

<h2>Conclusion</h2>

<p>Equality is hard to define simply even for a single language. It is easy to implement if you stick to a small set of common sense rules; more complicated implementations are possible but not in general recommended.</p>

<p>One key distinction is between values and references. You should know the difference between (polymorphic) reference types and value types in all languages and avoiding treating the two the same way! Equality for references is a check for identity but equality for value types is a check for equal values of all (significant) fields.</p>

<p>Making use of immutability for value types has many benefits, far beyond equality. In the case of equality though it allows for the possibility of caching of objects and/or values and it also removes the class of problems exemplified by the example of modifying an object while it is held in a collection.</p>

<p>Using value equality in a class hierarchy rarely makes sense and should be avoided. It is often better to avoid inheritance in the sort of cases where equality might make sense and use composition instead. Classes can also be made <code>final</code> (or <code>sealed</code>) to prevent unwanted inheritance but this can be an annoyance when a user of the class has a valid reason for wanting to extend your class.</p>

<h2>Further reading</h2>

<p>C# in a Nutshell has a deep exploration of equality in C#. For more about equality in Java see <a href="http://www.javapractices.com">http://www.javapractices.com</a>, and follow links through Overriding Object methods to implementing equals.</p>

<p>Angelika Langer and Klaus Kreft wrote a pair of articles on the subject [<a href="Love-Orr.xml#id(Langer)">Langer</a>]. While the target of their article is Java many of the points apply to C# as well.</p>

<h2>References</h2>

<p class="bibliomixed">[<a id="C# Equals"></a>C# Equals] <a href="http://msdn.microsoft.com/en-us/library/bsc2ak47%28v=VS.100%29.aspx">http://msdn.microsoft.com/en-us/library/bsc2ak47%28v=VS.100%29.aspx</a></p>

<p class="bibliomixed">[<a id="Java Equals"></a>Java equals] <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#equals%28java.lang.Object%29">http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#equals%28java.lang.Object%29</a></p>

<p class="bibliomixed">[<a id="Langer"></a>Langer] <a href="http://www.angelikalanger.com/Articles/JavaSolutions/SecretsOfEquals/Equals.html">http://www.angelikalanger.com/Articles/JavaSolutions/SecretsOfEquals/Equals.html</a></p>

<p class="footnote"></p>

<ul>
	<li><a id="FN01"></a>See <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html#valueOf%28int%29">http://download.oracle.com/javase/6/docs/api/java/lang/Integer.html#valueOf%28int%29</a></li>
</ul>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
