Overriding GetHashCode ..

A

Anders Borum

Hello!

I have a framework where all objects are uniquely identified by a GUID
(Global Unique Identifier). The objects are used in conjunction with lots of
hashtables and I was thinking, that overriding the GetHashCode base method
(inherited from object) was a good idea.

public abstract class CmsObjectNode : CmsObject, IXml
{
private Guid cmsObjectID = Guid.NewGuid();

public Guid CmsObjectID
{
get { return this.cmsObjectID; }
}

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

Comments?
 
J

Jon Skeet [C# MVP]

Anders Borum said:
I have a framework where all objects are uniquely identified by a GUID
(Global Unique Identifier). The objects are used in conjunction with lots of
hashtables and I was thinking, that overriding the GetHashCode base method
(inherited from object) was a good idea.

public abstract class CmsObjectNode : CmsObject, IXml
{
private Guid cmsObjectID = Guid.NewGuid();

public Guid CmsObjectID
{
get { return this.cmsObjectID; }
}

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

Comments?

Without overriding Equals, it's a very bad idea. Basically, you need to
make Equals and GetHashCode tie up together. If the CmsObject exposes
any properties used in testing for equality, those should probably be
part of the hash too.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top