Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8792575
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T22:59:51+00:00 2026-06-13T22:59:51+00:00

I’ve read the MSDN documentation on how Dictionary.ContainsKey() works, but I was wondering how

  • 0

I’ve read the MSDN documentation on how Dictionary.ContainsKey() works, but I was wondering how it actually makes the equality comparison? Basically, I have a dictionary keyed to a reference type* and I want the ContainsKey() method to check a certain property of that reference type as its basis for determining if the key exists or not. For example, if I had a Dictionary(MyObject, int) and MyObject has a public property (of int) called “TypeID”, could I get ContainsKey(MyObject myObject) to check to see if one of the keys has a TypeID that is equal to myObject? Could I just overload the == operator?

  • The reference type is an object called “Duration” which holds a value (double Length); “Duration” is a base type used in my music program to denote how long a particular sound lasts. I derive classes from it which incorporate more sophisticated timing concepts, like Western musical time signatures, but want all of them to be comparable in terms of their length.

EDIT: As suggested, I implemented IEquitable on my object like so:

 public class Duration : IEquatable<Duration>
 {
    protected double _length;

    /// <summary>
    /// Gets or Sets the duration in Miliseconds.
    /// </summary>
    public virtual double Length
{
        get
        {
            return _length;
        }
        set
        {
            _length = value;
        }
    }

// removed all the other code that as it was irrelevant

    public override bool Equals(object obj)
    {
        Duration otherDuration = (Duration)obj;
        if (otherDuration._length == _length)
        {
            return true;
        }
        else
        {
            return false
        }
    }

}

Is this all I need to do?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T22:59:52+00:00Added an answer on June 13, 2026 at 10:59 pm

    EDIT: here is code for your updated example. Note: I find it a little odd that you expose the field as protected, and also have a virtual property that exposes the member. Under this scheme something could override Length resulting in equality that looks at _lenght to not behave as expected.

    public class Duration : IEquatable<Duration>
    {
        protected double _length;
    
        /// <summary>
        /// Gets or Sets the duration in Miliseconds.
        /// </summary>
        public virtual double Length
        {
            get { return _length; }
            set { _length = value; }
        }
    
        // removed all the other code that as it was irrelevant
    
        public bool Equals(Duration other)
        {
            // First two lines are just optimizations
            if (ReferenceEquals(null, other)) return false;
            if (ReferenceEquals(this, other)) return true;
    
            return _length.Equals(other._length);
        }
    
        public override bool Equals(object obj)
        {
            // Again just optimization
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
    
            // Actually check the type, should not throw exception from Equals override
            if (obj.GetType() != this.GetType()) return false;
    
            // Call the implementation from IEquatable
            return Equals((Duration) obj);
        }
    
        public override int GetHashCode()
        {
            // Constant because equals tests mutable member.
            // This will give poor hash performance, but will prevent bugs.
            return 0;
        }
    }
    

    See EqualityComparer.Default for information on the default IEqualityComparer used by the Dictionary class.

    If you do not want to generally override GetHashCode and Equals on the class, or if you are unable to. There is an overload of the Dictionary constructor in which you can provide the specific IEqualityComparer to use.

    It is a simple interface to implement, but you do need to be careful that you respect the contract for GetHashCode or you can end up with unexpected behavior.

    public class MyObjectEqualityComparer : IEqualityComparer<MyObject>
    {
        public bool Equals(MyObject x, MyObject y)
        {
            return x.TypeID == y.TypeID;
        }
    
        public int GetHashCode(MyObject obj)
        {
            return obj.TypeID; //Already an int
        }
    }
    

    to use it just go

    new Dictionary<MyObject, int>(new MyObjectEqualityComparer());   
    

    If you want to use the default IEqualityComparer you need to provide roughly the same methods on MyObjectEqualityComparer. You can avoid overriding object.Equals() if you implement IEquatable. However I would strongly discourage it because doing so can create some surprising behavior. You are better of overriding Equals so that you have consistent behavior for all calls to Equals and have hashing that properly matches Equals. I have had to fix a bug in inherited code caused by a past developer only implementing IEquatable.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a French site that I want to parse, but am running into
I have an autohotkey script which looks up a word in a bilingual dictionary
This could be a duplicate question, but I have no idea what search terms
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
this is what i have right now Drawing an RSS feed into the php,
I have a small JavaScript validation script that validates inputs based on Regex. I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.