0

I have created an object, say details. I then assign: int x = details.GetHashCode();

Later in the program, I would like to access this object using the integer x. Is there a way to do this in C#?

Many thanks

Paul

7 Answers 7

7

No:

  • It may have been garbage collected, unless you've got something in place to stop that.
  • Hash codes aren't unique - what if there are two objects with the same hash code? (See Eric Lippert's post about hash codes for more information.)

You could create (say) a Dictionary<int, Details> and use the hash code as the key - but I'd strongly recommend that you didn't do that.

Any reason you don't want to just keep a reference to the object instead of the hash code?

Sign up to request clarification or add additional context in comments.

Comments

0

No.

A Hashcode represents some hashing function's value on the object.

You can't recreate the original object's refrence from this, and more importantly, there no guarantee that the object still exists.

Comments

0

If there is a way it would go against object orientation. You should expose the details reference to the consuming code.

Comments

0

Yes, you could create a Dictionary<int,Details> and store the object in this dictionary using the hashcode from details.GetHashCode( ) and then later on pull the object out of the dictionary using x.

But it's not something I would suggest doing! What is it you're trying to acheive?

Comments

0

Store the integer and just check the Hashcode again.

Note that in C# the Hashcode is not guarenteed unique. If you are dealing with a few million objects, you can and will run across duplicate hashes with the default implementation very easily.

http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx

"The default implementation of the GetHashCode method does not guarantee unique return values for different objects."

Comments

0
public static Detail GetDetailsFromHash(this List<Detail> detailsList, int x) {
    foreach (var details in detailslist) {
        if (details.GetHashCode() == x) {
            return details;
        }
    }
    return null;
}

However Hashcodes are not guaranteed to be unique

Comments

0

A hash code isn't really meant to be consumed directly. Its main purpose is so that the item can be used as a key in a collection. It is then the collections responsibility to map the hash back to the object. basically it lets you do something like Dictonary<details, myClass2> which would be much harder if GetHashCode wasn't implemented... but the function isn't a whole lot of use unless you are implementing your own collection or equality operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.