Generate HashCode in immutable type constructor

I have some questions about HashCode immutable types.

  • Can a "pre" generate a HashCode of an immutable type in the constructor or is there some reason not to do this?
  • Should I always generate Hashcode again when the GetHashCode () method is called?

Here is an example class:

    public class Id  {

        private readonly object _value;

        private readonly int _hash = -1;


        public Id( object value ) {
          _value = value;
          _hash = ( int ) ( 7 * value.GetType().GetHashCode() + 7 + 7 * _value.GetHashCode() );
        }

        public object Value {
          get {
            return _value;
          }
        }

        public override int GetHashCode() {
          return _hash;
        }

        public override bool Equals( object obj ) {
          Id other = obj as Id;

          if ( other == null ) {
            return false;
          }

          return this.GetHashCode() == other.GetHashCode();
        }
        }
+1
source share
3 answers

You can pre-create the hash code, but why? Just generate it if necessary (in GetHashCode), and then maybe save it. Most objects never require a hash, so it just slows down the program.

Hashcode , GetHashCode()?

- , , , , .

. Equals HashCodes. HashCodes (-).

+8

.

? , , , .

? , , , , , .

( , ) , GetHashCode , - . , , , , , GetHashCode. , .

+3

, : .

: , -.

, , - , , , .

+1
source

All Articles