Search code examples
c#listcontainsiequatable

IEquatable and inheritance


How would I make one parent and one child and inherit the IEquatable function for the child? here is my code

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 virtual bool Equals(Category other)
    {
        if (other == null)
            return false;

        if(this._Id == other._Id)
        {
            return true;
        }
        else { return false; }
    }
    
    public override int GetHashCode()
    {
        return this._Id.GetHashCode();
    }
}

public class SubCategory : Category :   
{
    public string parentCategory { get; set; }

    public SubCategory(string Name, string Id, string HomeCategory, bool inUse) : base(Name, Id, HomeCategory, inUse)
    {
    }
}

So I have to object and subcategory derives from category but contains method does not work with subcategory but it does with category. What am I doing wrong how would I derive the method of Category so that contains on a list with subcategory as its type would work?


Solution

  • SubCategory does inherit bool Equals(Category other), but it would apply to any Category instance- meaning that a SubCategory and a Category would be "equal" if they have the same Id.

    It sounds like you want an "automatic" implementation of IEquatable<SubCategory> and a bool Equals(SubCategory other) implementation, which is not possible. You'd need to explicitly add the interface declaration, but the implementation should be trivial:

    public class SubCategory : Category , IEquatable<SubCategory>  
    {
        public string parentCategory { get; set; }
    
        public SubCategory(string Name, string Id, string HomeCategory, bool inUse) : base(Name, Id, HomeCategory, inUse)
        {
    
        } 
    
        public bool Equals(SubCategory other)
        {
            return ((Category).this).Equals((Category)other)
        }
    }