Navigation
Links

Powered by Squarespace
« IPAddress class serializable? | Main | XML/object libraries are deprecated »
Thursday
Aug262004

Is it reference or value equality?

Probably reference. Checking for value equality is unintuitive - by default == is a reference equality check.
object a = 1;
object b = 1;
Assert.IsFalse (a == b);

Object a doesn't equal object b since boxing a as object created once instance, and boxing b created another. Since == is a "reference type equality operator", it will only compare the references.

Using any of these methods works fine:
Assert.IsTrue (a.Equals (b));
Assert.IsTrue (((int)a).Equals (b));
Assert.IsTrue (Object.Equals (a, b));
Assert.IsTrue ((int)a == (int)b);


When passing objects around, the simple solution is to use the Equals() method as it may perform value equality if the object overrides Equals(). So, value equality is somewhat easy to accomplish for individual objects, but you run into this problem again with collections:
Assert.IsFalse (
    new string[] { "abc", "def" }.Equals (
    new string[] { "abc", "def" }));
Assert.IsFalse (new int[] { 1, 2, 3 }.Equals (new int[] { 1, 2, 3 }));
Assert.IsFalse (
    new object[] { 4, "stuff", DateTime.Parse ("1/1/2004 1:00 AM") }.Equals (
    new object[] { 4, "stuff", DateTime.Parse ("January 1, 2004 01:00") }));


There is only reference equality with ArrayList since Object.Equals() is inherited not overridden.
Assert.IsFalse (
    new System.Collections.ArrayList (new int[] { 1, 2, 3 }) == 
    new System.Collections.ArrayList (new int[] { 1, 2, 3 }));
Assert.IsFalse (
    new System.Collections.ArrayList (new int[] { 1, 2, 3 }).Equals (
    new System.Collections.ArrayList (new int[] { 1, 2, 3 })));


Here's my solution to perform value equality for collections. And now:
Assert.IsTrue (Collection.Equals (
    new System.Collections.ArrayList (new int[] { 1, 2, 3 }), 
    new System.Collections.ArrayList (new int[] { 1, 2, 3 }), true));
Assert.IsTrue (Collection.Equals (
    new int[] { 1, 2, 3 }, new System.Collections.ArrayList (
    new int[] { 1, 2, 3 }), true));
Assert.IsTrue (Collection.Equals (
    new object[] { 1, 2, 3 }, 
    new int[] { 1, 2, 3 }), true);
Assert.IsTrue (Collection.Equals (
    new object[] { 4, "stuff", DateTime.Parse ("1/1/2004 1:00 AM") }, 
    new object[] { 4, "stuff", DateTime.Parse ("January 1, 2004 01:00") }), true);


Here's a real world example:
/// <summary>Always accepts the public key hardcoded in the byte array as a valid certificate.</summary>
public sealed class AcceptTrustedCertificate : ICertificatePolicy {
    public bool CheckValidationResult (
        ServicePoint srvPoint,
        X509Certificate certificate,
        WebRequest request,
        int certificateProblem) {
        //TODO: verify certificateProblem is an acceptable value
 
        // return true if certificate returned is equal to the certificate's public key
        return Collection.Equals (
            certificate.GetPublicKey (),
            new byte[] { 48, 130, 1, 10, 2, 130, 1, 1, 0, 206, 214, 212 }, true);
    }
}

Reader Comments (35)

I am sure this will be helpful for more than a handful of people. Nicely done.

September 4, 2004 | Unregistered CommenterDavid Collantes

Good job! Although isn't it possible to do the same using IComparable? In fact in generics using the dictionary stack (I think) is able to the same thing. However, this is based on a Key value pair, this is a nice low level equality check. There might be other generic classes in .NET 2.0 that might address this short coming. Again good stuff!

November 17, 2004 | Unregistered CommenterEddy Recio

Both the IComparable.CompareTo and IComparer.Compare method return if x > y, x = y, or x < y. This function only checks value equality for collections. I\'ve posted a RelaxComparer class that Implements the IComparer interface in a more relaxed way than the default Comparer class, and have implemented a CollectionEquality method that tests collection equality based on the value and count of each item in the collection, regardless of position.

December 2, 2004 | Unregistered CommenterGeorge Tsiokos

I really appreciate the information you have provided in this article.

Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you can do with a few pics to drive the message home a little bit, but instead of that, this is great blog. A great read. I will definitely be back.

Posting from a Job site - it's a reference not a value of equality. When you say value of equality, it must be represented with double equal sign.

November 11, 2011 | Unregistered CommenterJob Searcho

Hey there, interesting entry! i have bookmarked your blog so i can find it easily next time, looking forward for more post from you!!

November 17, 2011 | Unregistered Commentermedicare florida

Sorry for the huge review, but Im really loving the new Zune, and hope this, as well as the excellent reviews some other people have written, will help you decide if its the right choice for you. microchip microcontroller

November 19, 2011 | Unregistered CommenterHi

The background color and scheme of this blog is amazing, i really liked it.

This is exactly what I was looking for. Thanks for sharing this great article !

November 25, 2011 | Unregistered CommenterArticle writing software

I am glad to found such useful post. I really increased my knowledge after read your post which will be beneficial for me.

November 26, 2011 | Unregistered Commentertop toys for Christmas 2011

This is a good post. This post give truly quality information.I’m definitely going to look into it.Really very useful tips are provided here.thank you so much.Keep up the good works.

November 27, 2011 | Unregistered Commentersilver investment

This is one of the most informative information I've read. It really helps a lot. Thanks for sharing this and teaching soem of your Idea's.

November 27, 2011 | Unregistered Commentersafe disinfectant

Outstanding piece of work you have done.This type of posts is rarely found.This site has proved its metals in the way of giving extra ordinary information.Thank you so much for the great article.

November 27, 2011 | Unregistered Commentermurfreesboro seo

I am very glad that I find your regular post here. Which seems to be very important and it made good time pass for me. I will always give a nice thrust look in to you from my bookmark feed

November 27, 2011 | Unregistered Commentermurfreesboro painting

I really enjoyed this post and Thanx for the effort, keep up the good work Great work.

I appreciate your efforts to this article. I look forward to your release more of the same high-quality articles.

November 27, 2011 | Unregistered Commentermoonwalk nashville

I am so much excited after reading your blog. Your blog is very much innovative and much helpful for any industry as well as for person

November 28, 2011 | Unregistered Commentersave your marriage

Well done my friend, the blog is wonderful, keep on the good work my friend.

November 28, 2011 | Unregistered CommenterInternet Marketing Strategie

This is my top favorite blog which i like and appreciate from my hearth.

November 28, 2011 | Unregistered CommenterEspressomaschinen Test

This is the blog which is my top favorite blog, i really enjoy it every time.

November 29, 2011 | Unregistered Commentermurfreesboro audio rentals

This is my top favorite blog which i like most.

November 29, 2011 | Unregistered Commenterhosting

I read a lot of blogs on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say I’m glad I found your blog. basement sump pump solutions

December 2, 2011 | Unregistered CommenterAnonymous

I would like to appreciate the effort that you have put in making such an informative blog. I enjoyed this post of yours and I must say that every time I come back to your blog, I always have something new and informative to read. Thanks for keeping me updated.
average cost in finishing a basement

These facts are really interesting. Few of them were well known for me but many of them were brand new for me too! I will print this one out and show to my friends because they will be definitely interested in that

December 4, 2011 | Unregistered Commenterreverse mortgages canada

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>