zomgistania

Main page | About | Articles | Previous Posts | Archives

Monday, April 10, 2006

Comparing classes and structs = pain in the ass?

I had a huge problem trying to figure out what was wrong with dictionary.ContainsKey() and dictionary[key].Contains().

The functions weren't working at all, might I say. I had a custom key struct and a list of classes as the value in the dictionary.

The functions would never return true, even if I had just added the elements to the dictionary. Why? whywhywhywhy?


After a bit of searching from google groups, I came upon a post about something not even related which had stuff about overriding GetHashCode() and Equals().

I was thinking... "Does my struct/class actually have a way to compare itself?"
Nope. C# is clever, but not clever enough to create a GetHashCode() and Equals() function for your classes.


Here's a simple example on how to make your classes and structs easily comparable:


class Example
{
string a;
string b;

/* put constructor and stuff here */

public override int GetHashCode()
{
return a.GetHashCode() + b.GetHashCode();
}

public override bool Equals(object obj)
{
if(obj.GetHashCode() == this.GetHashCode())
return true;

return false;
}
}


So... basically you just make GetHashCode() take some hash values, for example from the variables in the class and return the sum. Built-in types have a working GetHashCode() defined.
Equals() just needs to compare the hashes and.. well, that's about it. I think this is a simple and effective way.



Powering my code tonight:
HurricaneFM
Radio Stad Den Haag

Both great internet radios.

0 Comments:

Post a Comment

<< Home