tags:

views:

72

answers:

7

Hi people, 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, wich is just that, a pair of data (string, float). I also have another class DataSet wich 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, wich 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?

Thanks!

+2  A: 

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.

onof
So I will have to resize it many times since I don't know the initial size. What about using a List?Thank you very much!
Tronfi
You have to use a List, but don't forget to initialize it.
onof
gnah too slow ;Dbut you are right, _datapair is null when he tries to insert the new datapair. A few advices: _datapair is a poor name for an array of datapairS, try _datapairs instead. And you should close the streamreader within a finally block or use the using statement or the file will stay open until your program closes if an exception happen in your try block. Btw: this sort of errors are easy to find with your debugger.
atamanroman
+1  A: 

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(...));

HTH,
Kent

Kent Boogaart
+1  A: 

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); 
}
ChaosPandion
+1  A: 

It's because your _dataPair array is not instantiated:

private DataPair [] _datapair = new DataPair[] { };
Prutswonder
+1  A: 

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()

PoweRoy
A: 

Use a list instead of array, since you do not know at compile time how many Datapair's you need.

mishal153
A: 

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.

Cipi