tags:

views:

150

answers:

2

Hi,

a class has an ID property and this property gets value from a primary key column of an SQL table.

Is it a good practice if I write

public override int GetHashCode()
{
    return this.ID + GetType().GetHashCode();
}

into my class? (Equals overrided already on the same way.)

+2  A: 

Why can't you just do

public override int GetHashCode() {
    return this.ID.GetHashCode();
}

I am not sure if what you are doing is good practice because I am not familiar with how the hash code is assigned to a type instance. And the purpose of the hashcode is to have a consistence representation of the object in Int32 form.

Nick Berardi
+3  A: 

Why would you particularly want to include the type in the hashcode? I can see how that could be useful if you had a lot of different types of object with the same ID in the same map, but normally I'd just use

public override int GetHashCode()
{
    return ID; // If ID is an int
    // return ID.GetHashCode(); // otherwise
}

Note that ideas of equality become tricky within inheritance hierarchies - another reason to prefer composition over inheritance. Do you actually need to worry about this? If you can seal your class, it will make the equality test easier as you only need to write:

public override bool Equals(object obj)
{
    MyType other = obj as other;
    return other != null && other.ID == ID;
}

(You may well want to have a strongly-typed Equals method and implement IEquatable.)

Jon Skeet
Thanks for both of you, +1 for the sealed idea.
boj