FAQ Database Discussion Community


Slow dictionary with custom class key

c#,string,dictionary,equals,gethashcode
I have a custom class that I was trying to use as a key for a dictionary: // I tried setting more than enough capacity also... var dict = new Dictionary<MyPoint, MyPoint>(capacity); Now let me be clear, the goal here is to compare two SIMILAR but DIFFERENT lists, using X,...

Conditionally change GetHashCode() when comparing two objects

c#,.net,performance,comparison,gethashcode
I have two different lists of objects and want to get their similarities, based on the weight of some of the properties. Quickest way seems to be with implementing an IEquatable interface and that is what have I done: public class CompareEntry : IEquatable<CompareEntry> { public int LeadId { get;...

C#, Which class fields/members should be considered when overriding GetHashCode and Equals?

c#,equals,gethashcode,iequatable
There is this excelent question and answer about this topic: Do I HAVE to override GetHashCode and Equals in new Classes? As it mentions: you only need to override them if you need value equality semantics. The System.Object implementation isn't 'bad', it just only does a reference check (which is...

Is there any negative consequence in having Equals based on GetHashCode?

c#,.net,equals,gethashcode
Is the following code OK? public override bool Equals(object obj) { if (obj == null || !(obj is LicenseType)) return false; return GetHashCode() == obj.GetHashCode(); } public override int GetHashCode() { return Vendor.GetHashCode() ^ Version.GetHashCode() ^ Modifiers.GetHashCode() ^ Locale.GetHashCode(); } All the properties are enums/numeric fields, and are the only...

Substitute the GetHashCode() Method of System.Drawing.Point

c#,performance,gdi+,gethashcode
System.Drawing.Point has a really, really bad GetHashCode method if you intend to use it to describes 'pixels' in a Image/Bitmap: it is just XOR between the X and Y coordinates. So for a image with, say, 2000x2000 size, it has an absurd number of colisions, since only the numbers in...

Handling collections in GetHashCode implementation

c#,generics,collections,gethashcode,iequatable
I'm working on implementing GetHashCode() based on the HashCode struct in this answer here. Since my Equals method will consider collections using Enumerable.SequenceEqual(), I need to include the collections in my GetHashCode() implementation. As a starting point, I'm using Jon Skeet's embedded GetHashCode() implementation to test the output of the...