user1164199
user1164199

Reputation: 379

Adding elements to an array in C#

I am a newbie to programming c# and I want to add an element to an array.

Here's my function:

public bool AddPlayer(string PlayerName,string token)
{
    static int i = 0;  // <---- Error

    if ( PlayerIndex < MAX_NUMBER_OF_PLAYERS )
    {          
        Player[i]= PlayerName
        i++;
    }

    return true;
} 

The static int i = 0 results in an error. Is there another way to do this?

Upvotes: 0

Views: 350

Answers (6)

Ravi Gadag
Ravi Gadag

Reputation: 15851

you can change "i" as Static class member, or you can change the function to a static method

public static bool AddPlayer(string PlayerName,string token)

Upvotes: 0

BrokenGlass
BrokenGlass

Reputation: 160852

It sounds like you don't really know how many players you are going to store (up to a maximum). In this case you should rather use a List<string> to store your player names, which will resize to fit any number of players:

private List<string> players = new List<string>();

public void AddPlayer(string playerName,string token)
{
   players.Add(playerName);
}

Upvotes: 3

Komi Golov
Komi Golov

Reputation: 3471

The usual way to do this is to use a List, not an array. However, assuming you can't do that, you should make the index a (non-static) member of the class and initialise it to 0 in the constructor.

Upvotes: 1

Keith Nicholas
Keith Nicholas

Reputation: 44288

if you use List instead of an array.... (its far more likely a List will serve you better)

you can go Player.Add(PlayerName);

eg

var players = new List<string>();

players.Add("bob");
players.Add("mary);

but most likely you will want a player class, so you can add other interesting bits of information about "players".

class Player
{
    public string Name { get; set; }
}

then

var players = new List<Player>();

players.Add(new Player() { Name = "bob" });
players.Add(new Player() { Name = "mary" });

Upvotes: 1

Jeff LaFay
Jeff LaFay

Reputation: 13350

If you actually need a static variable then you need to define it outside of the method and within the class definition.

static int i = 0;

public bool AddPlayer(string playerName, string token)
{
    // method implementation here...
}

Upvotes: 0

Andrew Cooper
Andrew Cooper

Reputation: 32576

You'll need to make i a static class member, not a local variable in the method. You probably want to give it a more meaningful name, too.

Upvotes: 0

Related Questions