Ahmad Abdullah Awayhan Ahmad Abdullah Awayhan - 1 month ago 13
C# Question

c# How to use an instanciated object's property(which is a list) in a function?

I have two classes.
A Player Class that has the properties Name, Balance and Cards:

class Player
{
public string Name;
public decimal Balance;
public List<Card> Cards; // My question is related to this property
}


And a Card class:

class Card
{
public string Name;
public int Attack;
public int Defense;
public decimal Cost;
}


I instantiated an object for the player:

var player = new Player("Ahmad", 100);


and also a card:

var card = new Card("Mino", 3, 3, 200);


then added the card to the player's Cards:

player.Cards[0] = card;


I can simply display it on the main method where it was instantiated but the Problem is: How can I access the player's Cards in a function? like so:

///<summary>
/// Function to show current cards
/// </summary>
public static void ViewCards(object player)
{
var cards = player.Cards // This line doesn't work
foreach (var card in cards)
{
Console.WriteLine($"{card.Name}");
Console.WriteLine($"Attack: {card.Attack}");
Console.WriteLine($"Defense: {card.Defense}");
Console.WriteLine($"Cost: ${card.Cost}");
}
}

Answer

Change the method signature Change the player parameter , from Object to Player

public static void ViewCards(Player player)
{
}