Newbie Mistake — Object Equality


I made a newbie mistake.

This is similar to some code I just wrote. Can you spot the mistake?

(HINT: the code compiles; I made a logic mistake not a syntax mistake):

using System;
using System.Collections.Generic;

public class Program
{
static void Main(string[] args)
{
var d1 = new Dictionary<Foo, string>();
var key = "hi";
var foo = new Foo(key);

d1.Add(newFoo(key), "whatever");
Console.WriteLine("d1 key == d2 key? {0}", d1.ContainsKey(foo))
Console.ReadKey();
}
}

public class Foo
{
public Foo(string fooString)
{
_fooString = fooString;
}

public string FooString
{
get { return _fooString; }
}

// ...

private readonly string _fooString = "";
}


Answer:

The problem is with the ContainsKey() method on the d1 object (of type Dictionary).

I expected the result to be “true” because I was thinking that the VALUE OF THE KEY is the same for d1 and d2 (i.e. “hi”).  But what I forgot is that ContainsKey() is not testing for equality of the VALUE OF THE KEY, but for equality of the key itself (the key object).  And in this case, the key object for d1 is a DIFFERENT OBJECT than the key object for d2.

Note a slight subtly, when I refer to my mistakenly comparing the “value of the key” I am NOT referring to the value of the key/value pair.   I am referring to my mistakenly comparing the private literal member field (_fooString).

In pseudo-code: d1.key.stringValue == d2.key.stringValue BUT d1.key != d2.key

Therefore, ContainsKey() returns false.

Beginner Aside: A Dictionary is a mapping of key/value pairs.  Keys must be unique and each key maps to a value (often a value could be another data structure/object).  Dictionary data structures are commonly used when you are working with data that is not stored sequentially (unsorted) and need fast lookup times (at the small expense of data insertion/write times).   Compare this to a List, in which insertion is fast (just plot the new data on the end) but looking up data is slower because the list must be traversed sequentially until you find the data you are looking for.

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 )

Google+ photo

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

Connecting to %s