Aviv Yaari
Aviv Yaari

Reputation: 13

c#: Accessing object properties in Extension Methods

I'm currently writing a c# Rummikub game.

I have an object named Card that has Value and Color properties. Also, inside Player's Class, I have a list of cards (player's hand).

In the Player class, I wrote some methods that get only the player's hand as parameter. stuff like:

    // Determines what card should the CPU throw.
    public int CardToThrow(List<Card> CPUHand).

    // Call:
    int cardToThrow = Player1.CardToThrow(Player1.Hand);

I want to be able to call the function like this:

    int cardToThrow = Player1.Hand.CardToThrow();

When I tried to write the Extension Method, I didn't manage to acces the card's properties:

public static class HandExtensionMethods
{
    public static int foo<Card>(this List<Card> list)
    {
        return list[0].Value;
    }

}

Error:

'Card' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'Card' could be found (are you missing a using directive or an assembly reference?)

How should I write the extension methods so I could access the object properties?

Upvotes: 1

Views: 853

Answers (1)

Lee
Lee

Reputation: 144126

Your extension method is generic with a parameter type of Card which is shadowing the concrete Card class. Remove the generic parameter:

public static int foo(this List<Card> list)
{
    return list[0].Value;
}

Upvotes: 5

Related Questions