Zink Zink - 3 months ago 5
C# Question

Change a line of code in a while loop

Beginner in C# here. I was wondering if the following is even possible in c#.

I have the following code that works (but does not do much as of now):

while (i != 10)
{
i++;
_playerCard1.Source = new BitmapImage(new Uri($"ms-appx:///Assets/card {cardsInHand[cardsInHand.Count - 1].Face}.gif"));
}


Now I have other Image fields in my program named _playerCard2, _playerCard3 and so on. What I wanted to know was if I could have the while loop iterate through the different Image fields using the i variable. Something like this:

while (i != 10)
{
i++;
_playerCard{i}.Source = new BitmapImage(new Uri($"ms-appx:///Assets/card {cardsInHand[cardsInHand.Count - 1].Face}.gif"));
}


I know the above code will not work, just wondering if it even is possible and if so how would I code it? Thank you for all your help!

Answer

What you need is an array or list of playerCard then you can iterate each item. For example.

//create a simple array of cards
var playerCards = new[] { _playerCard1, _playerCard2, _playerCard3 }; 

//iterate each card
for(var i = 0; i < playerCards.length; i++)
{
    _playerCards[i].Source = new BitmapImage(new Uri($"ms-appx:///Assets/card {cardsInHand[cardsInHand.Count - 1].Face}.gif"));
}
Comments