1
public class Date
{
    public int mm;
    public int dd;

    public Date(int get_mm, int get_dd)
    {
        mm = get_mm;
        dd = get_dd;
    }
}

public Dictionary<Date, int> dictionary = new Dictionary<Date, int>();

Date A = new Date(1,1)
Date B = new Date(1,1)

dictionary.Add(A,1);
if(dictionary.ContainsKey(B)) //returns false
...

How do i override the Date class in this situation? I know the 2 objects is not the same, but don't know how to make it work

gaborbozo
  • 7
  • 5
  • 3
    You need to override the `Equals` and `GetHashCode` methods of `Date`. Or you can create an `IEqualityComparer` to pass to the Dictionary to tell it how to compare the `Date` obejcts. – juharr Mar 26 '20 at 13:14
  • The best way to do is make the dictionary with a custom equality comparer. [Check this](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.-ctor?view=netframework-4.8#System_Collections_Generic_Dictionary_2__ctor_System_Collections_Generic_IEqualityComparer__0__) – Magnetron Mar 26 '20 at 13:17
  • Why do you want to get object B rather than object A from your exaple? A + B share the same values so why're you saving them twice? – user743414 Mar 26 '20 at 13:21
  • @user743414 It's just an example. I just wanted to reflect my problem – gaborbozo Mar 26 '20 at 13:37
  • @gaborbozo That's why I was asking what you're trying to do. – user743414 Mar 27 '20 at 08:38

1 Answers1

1

You have 2 ways :

  • By overriding the GetHashCode and Equals method of you class Date.
  • By using the Dictionary constructor that accepts one IEqualityComparer<Key> as argument.

It is not recommended to use the first method if your Date object is not immutable (i.e. that its attributes can't be modified after its creation => Date attributes need to be readonly). Because the Dictionary class builds its internal structure based on GetHashCode value at insert time. If the attributes used to compute the GetHashCode change, you won't be able to retrieve your objects already inserted in the dictionary.

Bioukh
  • 1,888
  • 1
  • 16
  • 27