FastCow FastCow -4 years ago 69
C# Question

Fill a list from another class

I have these classes:

class Game
{
public List<Participant> Participants = new List<Participant>();
}

class Participant
{
public int ChampionId { get; set; }
public string SummonerName { get; set; }
public int SummonerId { get; set; }
}

public class APICalls
{
//private Game game;

private string GetResponse(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

WebResponse response = request.GetResponse();

using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}

public void GetParticipants()
{
// create a string from the JSON output
var jsonString = GetResponse("https://euw1.api.riotgames.com/lol/league/v3/positions/by-summoner/27528610?api_key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

// fill the Participants list from the Game class with participants based on the contents of the jsonString variable
Game.Participants = JsonConvert.DeserializeObject<Game>(jsonString);


}

}


I want to fill my Participants list in the Game class with the GetParticipants method in the APICalls class. My problem is that I can't access the list from this class.

I would like to keep all my API code in one class file which is why I made this class.

What am I doing wrong?

Answer Source

Either create an object of Game and refer to Participants using game.Participants as shown below:

Game game = new Game();
game.Participants = JsonConvert.DeserializeObject<Game>(jsonString);

Or

Make the Participants list static:

class Game
{
    public static List<Participant> Participants = new List<Participant>();
}

And access the Participants list it directly then using Game.Participants

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download