Hi I am trying to add in IEquatable to my program and I have no clue if I need to add a unique id basicly and a hashcode? They are using the shd number as a unique id in the IEquatable but they give the value to it in the constructor and I asked on this site if the constructor was needed to look like it does in the documentation and I got a no. So now I am confused can someone give me an easier example of IEquatable then the documentation does? here is the link for the documentation https://learn.microsoft.com/en-us/dotnet/api/system.iequatable-1?view=netcore-3.1 I am just trying to get contains for a custom object list to work.
My code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataConverter.Objects
{
public class Category : IEquatable<Category>
{
public string _Name { get; set; }
public string _Id { get; set;}
private string _HomeCategory { get; set; }
public string _prestaId { get; set; }
public bool _inUse { get; set; }
public Category(string Name, string Id, string HomeCategory, bool inUse)
{
_Name = Name;
_Id = Id;
_HomeCategory = HomeCategory;
_inUse = inUse;
}
public bool Equals(Category other)
{
if (other == null)
return false;
if()
}
}
}
IEquatable<T>is just an interface that tells you that the current type has value equality semantics, not reference equality. What the logic is behind what makes two distinct objets equal or not is completely dependant on the business logic of your application, not how you correctly or incorrectly implement the interface.What makes two categories be the same in your domain? The same
Id? Then your equals method would be:The same Id and name?
And so on. Its you who decides what makes two categories equal each other.
Now, about the hash code. The basic rule a hash code must comply with is: Two categories that are equal must have the same hash code. Do note that this does not mean that two categories with the same hash code are equal, hash codes can collide, there is no problem with that at all. Also, hash codes should not change if the object changes, so ideally they should be built upon data that can not be changed.
Ok, so how would you implement your hash code in your particular scenario?
Case 1:
Case 2:
Both hashes will be consistent with their
Equalscounterpart. The only problem is that they are built on potentially mutable data (both Id and Name have setters) so if any of those change, your haschcode would change too, and that is usually a bad idea.Depending on your scenario you might have to deal with this problem differently. Is your data likely to mutate while performing any hash sensitive operations? Linq for example used hashes quite extensively...