WDUK
WDUK

Reputation: 1524

Get object data outside for loop in C#

I'm really new to C#, I started with Javascript so it's a bit of a struggle to understand the behaviour of C#.

I am trying to create a simple object inside my for loop and then display the assigned value afterwards but there is a scope issue with this, and am unclear on how I can then access it outside of the for loop?

This is my code setup:

public class Player{
    public int identity;
    public int score;

    public Player(int id){
        identity = id;
        score    = 0;
    }
}
for (int i = 0; i < max; i++){
        Player player = new Player(i);
}

//here i want to access a player and print the information for said player

I don't know how i can access the newly created players outside of the loop, how is this done?

Upvotes: 1

Views: 797

Answers (2)

CodingGorilla
CodingGorilla

Reputation: 19872

I can understand how this could be confusing coming from JavaScript, in JavaScript all your variables are hoisted to the function (or global) scope. That's not true in C#, in C# variables are generally scoped within the nearest set of {}s. But are available for use within child scopes.

So you could write your code like this:

List<Player> players = new List<Player>();
Player player = null;
for (int i = 0; i < max; i++){
        player = new Player(i);
        players.Add(player);
}
Console.WriteLine(players[x]);

In this example you would have access to each individual player outside of the foreach because it's declared at the higher scope. But this would be more appropriately written:

List<Player> players = new List<Player>();
for (int i = 0; i < max; i++){
        Player player = new Player(i);
        players.Add(player);
}
Console.WriteLine(players[x]);

It's generally considered good practice to declare your variables as close to their usage as you can.

A final optimisation, that you yourself suggested, would be to eliminate the player declaration completely (as it's unnecessary) and inline it. That leaves us with the final version:

List<Player> players = new List<Player>();
for (int i = 0; i < max; i++){
        players.Add(new Player(i));
}
Console.WriteLine(players[x]);

Upvotes: 6

Midhun Mundayadan
Midhun Mundayadan

Reputation: 3192

you can try something like this

Player player = new Player();
List<Player> playerlist = new List<Player>();

for (int i = 0; i < max; i++){
      player   = new Player(i);
      playerlist.Add(player);
}

Upvotes: 2

Related Questions