I am working on a program (learning C#) that creates a object (Card) and in the program it sorts the deck of cards by value. What I am baffled by is how it is able to sort a deck of cards by the value of the cards when the instance of the object isn't the parameter passed to the method but the class object. Below is the code to help answer my question - I would complete follow this if I was passing the instantiated object.
The class to create the object:
class Card
{
public Suits Suit { get; set; }
public Values Value { get; set; }
public Card(Suits suit, Values value)
{
this.Suit = suit;
this.Value = value;
}
public string Name
{
get { return Value.ToString() + " of " + Suit.ToString(); }
}
public override string ToString()
{
return Name;
}
}
In another class I am calling the method that instantiate a object(CardComparer_byValue) that inherits from interface IComparer. This is where my confusion comes in.
public void SortByValue() {
cards.Sort(new CardComparer_byValue());
}
And the SortByValue Class
class CardComparer_byValue : IComparer<Card>
{
public int Compare(Card x, Card y)
{
if (x.Value > y.Value)
return 1;
if (x.Value < y.Value)
return -1;
if (x.Suit > y.Suit)
return 1;
if (x.Suit < y.Suit)
return -1;
return 0;
}
}
I would think the above method "SortByValue" was called like this
Card mycard = new Card("Spades", 4);
public void SortByValue() {
cards.Sort(new CardComparer_byValue(mycard));
}
So would someone explain to me what I am missing on how the sort can work this way?