I want to use the following object as a dictionary. If Category and Target are equal, the key is equal. Any solution?
public class TargetKey { public TargetKey(Categories category_arg, String target_arg) { catetory = category_arg; target = target_arg; } private Categories catetory; public Categories Catetory { get { return catetory; }
Bad decision
It seems that GetHashCode() is called first, if the hash is equal, then Equals() is called. Therefore, I add the following 2 methods:
public override bool Equals(object obj) { TargetKey other = obj as TargetKey; return other.Catetory == this.Catetory && other.Target == this.Target; } public override int GetHashCode() { return 0;
Refined solution
public override bool Equals(object obj) { TargetKey other = obj as TargetKey; return other.Catetory == this.Catetory && other.Target == this.Target; } public override int GetHashCode() { Int32 hash = this.Target.GetHashCode() + this.Catetory.GetHashCode();
source share