I would like to ask some rather basic question (I presume) the answer to which seems to elude me. In the following code I am trying to load an array with a csv file (; separated) that contains two columns (string Name, int Score
).
For simplicity I have commented out the loop I want to use to transfer this file onto an array and I am just loading the 2nd element. For some reason unless I use (scoreobj[1] = new HighScore();
) I get a null
reference.
Why do I need to do that? Haven't I already initialized the scoreobj[]
object at the beginning?
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WindowsFormsApp1
{
public class HighScore
{
public string Name { get; set; }
public int Score { get; set; }
public static void LoadHighScores(string filename)
{
string[] scoredata = File.ReadAllLines("C:/Users/User/Desktop/Test.csv");
HighScore[] scoreobj = new HighScore[scoredata.Length];
scoreobj[1] = new HighScore();
scoreobj[1].Name = scoredata[1].Split(';')[0];
//for (int index = 0; index < scoredata.Length; index++)
//{
// scoreobj[index].Name = scoredata[index].Split(',')[0];
// scoreobj[index].Score = Convert.ToInt32(scoredata[index].Split(';')[1]);
//}
Console.WriteLine(scoreobj[1].Name);
}
}
}