1

I have created a class named "Player" which stores data for each player. The class does what it should do, but when storing multiple instances of the class in a List/Array, all objects in the array or list are equal to the last stored object.

Player class code:

public class Player
{
    private static string player_name;
    public Player(string name)
    {
        player_name = name;
    }
    public string Name
    {
        get
        {
            return player_name;
        }
    }
}

code for creating and adding to the list:

//simple string array for names;
string[] example_names = new string[] { "Mike", "Adam", "Jake" };

//creating new object and adding to list<Player>
List<Player> players = new List<Player>();
foreach (string name in example_names)
{
     Player player = new Player(name);
     players.Add(player);
}

//loop for returning the output
string output = "";
foreach (Player player in players)
{
    output += player.Name + ", ";
}
Clipboard.SetText(output);

output: "Jake, Jake, Jake, "

1
  • 2
    player_name shouldn't be static Commented Jul 15, 2015 at 16:16

1 Answer 1

9

Remove static from private static string player_name; in class Player. With that keyword, you are specifically telling it to make all instances of Player have the same name.

Without it, name will be an instance field, and can be set and retrieved separately for every instance of Player.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.