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);
}
}
}
HighScore. You could even create an instance of a derived class and put it into the exact same array. How would the compilr in this case know which class you want to instantiate? It can´t and thus won´t. So you have to create the instance yourself. But even without a derived class, your constructgor may have paramaters, which compiler can´t guess - e.g.new HighScore(name, score).Haven't I already initialized the scoreobj[] object at the beginning...yes, you have. But that just initialises the array, it doesn't initialise the contents (at least not beyond setting some default values for them, which, for classes etc is always null).