user2740565
user2740565

Reputation: 67

add a Number to an array of strings

I made this Object Player(int number, string name, string guild, int hp, int mana) And from a CSV File I'm reading a list of Players.

   public static List<Player> GetPlayerFromCSV(string file)
    {
        List<Player> result = new List<Player>();
        using (StreamReader sr = new StreamReader(file))
        {
            string line = sr.ReadLine();
            if (line != null) line = sr.ReadLine();

        while (line != null)
        {
            Player pl = AddPlayer(line);
            if (pl != null) result.Add(pl);
            line = sr.ReadLine();
        }
    }
    return result;
}

private static Player AddPlayer(string line)
{
    line = line.TrimEnd(new char[] { ';' });
    string[] parts = line.Split(new char[] { ';' });

    if (parts.Length != 5) return null;

    Player pl = new Player(parts[0], parts[1], parts[2], parts[3], parts[4]);
    return pl;
}

public override string ToString()
{
    return Number + "  -  " + Name;
}

It gives me an error because parts 0, 3 and 4 should be strings, since it's an array of strings. I already tried parts[0].ToString() etc, but it's no help

Upvotes: 0

Views: 90

Answers (1)

D Stanley
D Stanley

Reputation: 152521

You need to parse the strings:

Player pl = new Player(int.Parse(parts[0]), 
                       parts[1], 
                       parts[2], 
                       int.Parse(parts[3]), 
                       int.Parse(parts[4])
                      );

But that's the bare minimum - I would also move the parsing to separate statements before the Player construction you you could add error checking/validation/etc.

As it stands now, if parts 0, 3, or 4 are not parsable, you'll get a vague run-time exception with no context as to which value causes the error.

Upvotes: 4

Related Questions