I’m totally new to C# and I’m having an error that I can’t guess why its happening. This is the context:
I have a DataPair class, which is just that, a pair of data (string, float). I also have another class DataSet which is an array of DataPairs.
DataSet has two private members:
private DataPair [] _datapair;
private int _size;
The constructor of DataSet does nothing with _datapair and set _size to 0.
I fill the DataSet with a method Append, which does something like this:
public void Append(DataPair pair)
{
_datapair[_size] = new DataPair(pair);
_size++;
}
I call Append from another method, FillFromFile:
public void FillFromFile(string filepath)
{
try
{
if (System.IO.File.Exists(filepath))
{
System.IO.StreamReader sr = new System.IO.StreamReader(filepath);
string[] currentdata;
while (sr.Peek() >= 0)
{
currentdata = sr.ReadLine().Replace(',', '.').Trim().Split(';');
this.Append(new DataPair(currentdata[0], System.Convert.ToSingle(currentdata[1])));
}
sr.Close();
}
}
catch (Exception e)
{
Console.WriteLine("Error in datafile: {0}", e.ToString());
}
}
It seems that it should work: It creates (new) a new DataPair for each Append.
But I get this error when executing:
"Object reference not set to an instance of an object" in function Append.
What is happening?
Probably _datapair is not initialized yet. You call _datapair[_size] directly that isn’t initialized yet.
Why not use a Collection btw?
_size is then obsolete, you can use _datapair.Count()