Overriding CompareTo() in an object

Hello!

I’m making a card game program that has a List<Card> as a member of a Deck class. I’d like to be able to enforce unique cards being added to this list, which I’d like to do by overriding the CompareTo() method of the Card class. Right now, I have:

public override bool Equals(Object obj){ if (obj = null | GetType () != obj.GetType ()) { return false; } Card c = (Card)obj; return Name == c.Name; } 

where Name is a string property of Card. I have the complimentary override of GetHashCode() returning Name.GetHashCode().

This should “work”, but has the potential to be abused or create bugs by someone introducing Cards with the same Name but otherwise different Card properties. Can anyone recommend a better way to accomplish my goal?

TLDR: how do I enforce non-duplicates in a List, without resorting to a HashTable or Dictionary?

submitted by /u/NirodhaDukkha
[link] [comments]

Leave a Reply