Equals() and GetHashCode() for Custom Objects in VB

Seekers,

.Equals() is a strange animal. It’s used like:

And for standard objects it works fine:

The are equal.

But what about something non-standard?

Should be pretty easy.. We’ll just make 2 objects, both having I equal the same thing… We’ll compare with:

Result? in-equal Whuh?

They aren’t different, really, are they?

Well, yes, but the reason why is long & boring and we really don’t care in the end. We just need a way to get around the .NET internals so when WE think 2 objects are equal, they really are considered so by our programs.

So the only question that remains is: How does .NET compute equality?

Actually, the answer is: Pretty simply! There are 2 things that are used, and they both live on your instantiated objects already.

Have you ever scrolled down an object’s list of methods & variables and seen a few yuo never mess with? How about .Equals and .GetHashCode?

2014-06-19_Screenshot_237

For our simple class, we know what .ToString and .I do, but what about those others we always breeze by without noticing?

.Equals() – Returns a Boolean after determining if the 2 objects are equal (A.Equals(B))

.GetHashCode() – Returns an integer representation of a Hash of the object. Not perfect, but fast & good enough to determine equality by comparison.  2 different objects will produce (virtually) different hashes.

.GetType() – Returns a System.Type that says what kind of class this instance came from. In our case, the Foo() class.

“Equality” is based on the results of the GetHashCode function. Luckily, we can override them!

Here then is a complete example that shows how to override not just GetHashCode & Equals, but also ToString:

Note: Just holler if I need to explain any of it, OK?

pat
:)

Leave a Reply

Your email address will not be published. Required fields are marked *