0

I have a class Money and I want to know what the best way of implementing GetHashCode on this value class would be give that $1 != €1. Having a weighted value against the currency * value is not going to work.

public class Money : System.IEquatable<Money>
{       
    public Money(Currency c, decimal val)
    {
        this.Currency = c;
        this.Value = val;
    }

    public Currency Currency
    {
      get; 
      protected set; 
    }

    public decimal Value 
    { 
      get; 
      protected set; 
    }

    public override bool Equals(object obj)
    {
        Money m = obj as Money;

        if (m == null){throw new System.ArgumentNullException("m");}

        if(m.Currency.Id == this.Currency.Id)
        {
            if(m.Value == this.Value)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    public override int GetHashCode()
    {
        // What would be the best way of implementing this as €1 != $1
        // Currency object contains 2 members, (int) Id and (string) symbol
    }
}
user1054637
  • 695
  • 11
  • 28

1 Answers1

0

As the Currency.Id seems unique, provided it's a non-zero integer I'd go with

public override int GetHashCode()
{
    unchecked
    {
        return (Currency.Id*397) ^ Value.GetHashCode();
    }
}

Would Currency.Id be a not-empty string or a Guid, the following would do the trick

public override int GetHashCode()
{
    unchecked
    {
        return (Currency.Id.GetHashCode()*397) ^ Value.GetHashCode();
    }
}
nulltoken
  • 64,429
  • 20
  • 138
  • 130