While initializing, it says "Object reference not set to an instance of an object"
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 ar开发者_JAVA百科ray 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?
You have not initialized _dataPair. _datapair = new DataPair[size];
Anyway the code in Append is wrong. You cannot increase the size of an array in that way. Maybe is better that you use a List<DataPair>
instead of an array.
Probably _datapair is not initialized yet. You call _datapair[_size] directly that isn't initialized yet. Why not use a Collection btw?
private List<DataPair> _datapair = new List<DataPair>();
public void Append(DataPair pair)
{
_datapair.Add(pair);
}
_size is then obsolete, you can use _datapair.Count()
I would use List<DataPair>
like this:
private readonly List<DataPair> _datapair = new List<DataPair>();
Then your append method simply becomes:
public void Append(DataPair pair)
{
_datapair.Add(pair);
}
It's because your _dataPair array is not instantiated:
private DataPair [] _datapair = new DataPair[] { };
Your code creates a new DataPair
, but never initializes the DataPair
array. Thus, datapair refers to null and any attempt to dereference it will result in a NullReferenceException
. You'll need initialize it before accessing it:
_datapair = new DataPair[someSize];
I think you'll be better off with a list, though, since arrays do not automatically resize themselves:
private readonly IList<DataPair> datapairs;
...
datapairs = new List<DataPair>();
...
datapairs.Add(new DataPair(...));
Use a list instead of array, since you do not know at compile time how many Datapair's you need.
You don't need to make new DataPair
in Append
, since you already created the DataPair
object in a call to Append
, so you can only do this:
public void Append(DataPair pair)
{
_datapair[_size] = pair;
_size++;
}
Also, _size
is unnecessary since all C# arrays count their elements. You are better off using List, or if you insist on array, you could do this:
public void Append(DataPair pair)
{
_datapair[_datapair.Count()] = pair;
}
And, error you get is thrown when Append
tries to add new object to _datapair
array which is not array, but uninitialized reference to array of DataPairs. So as the answers below say, you must initialize array, but you must know its maximum or wanted size:
private DataPair [] _datapair = new DataPair[10];
Since I believe you don't know the size, you should use List instead of you array.
private List<DataPair> _datapair = new List<DataPair>();
public void Append(DataPair pair)
{
_datapair.Add(pair);
}
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());
}
}
If you want to know the size of list, call _datapair.Count()
, if you want to access the 4th element in list, _datapair[4] = null
.
精彩评论