bb441db
bb441db

Reputation: 294

All objects in array are equal to last added object c#

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, "

Upvotes: 1

Views: 70

Answers (1)

Jashaszun
Jashaszun

Reputation: 9270

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.

Upvotes: 9

Related Questions