3

I'm working on writing a compiler for a language running on .net and one of the things I would like it to do is to automatically generate the GetHashCode method, but I have several questions:

  • Is this possible, does the compiler know enough about the type(s) involved to do a reasonable job implementing the method?
  • Should I do this for value types, reference types, or both?
  • What is a reasonable GetHashCode algorithm for the compiler to generate which includes support for null properties and so forth?
  • Has this been done in another language/compiler that I can look at?
  • If this isn't possible or is a really bad idea, why?

Thanks

1 Answer 1

2

Have a look at what the C# compiler does for anonymous types. Basically it's the same sort of hash as I'd write myself:

public override int GetHashCode()
{
    int hash = 17;
    hash = 31 * hash + field1.GetHashCode();
    hash = 31 * hash + field2.GetHashCode();
    // etc
    return hash;
}

(You need some nullity checking as well, of course.)

I think it's a good idea to do this (and equality override) for immutable types, but generally not for mutable types. Value types should almost always be immutable anyway - reference types can go either way. Does your language have any built-in notion of immutability? Of course, this will go wrong if your type is "shallow immutable" but contains mutable types which override GetHashCode to indicate the current state of the object. Such types would generally be painful anyway.

In general though, I think it's reasonable in many cases to autogenerate equality and hash codes - indeed, I'd like this to be part of C# 5 for named types too: I want an easy way of naming types which otherwise have the same features as anonymous types.

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

2 Comments

The language doesn't have built-in immutability, picture a c#-3-like language. Would nullity checking just be, if null don't call GetHashCode or is there more to it?
@wawa: That's pretty much it. Use some constant (e.g. 0) for fields that have a null value.

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.