0

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

1
  • Now I'm just sending the ints through as strings, but I don't know if that's the correct way to approach this Commented Sep 3, 2013 at 17:32

1 Answer 1

4

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.