Search code examples
c#arrayscustom-lists

Access updated array from constructor


I have a parameterized constructor and a default constructor. They both create a new object array with x length, however, when I try to access the array in the Add method, it returns the value "null". I can't initialize the array in the fields because I don't know what size the user wants it to be, but I don't know how to access the 'updated' array later in the code. I get a NullReferenceException() on the line of code: if (count > data.Length) because data has the value null.

class CustomList
{
    private int count;
    private String[] data;

    public int Count
    {
        get { return count; }
    }
    public CustomList(int arrayNum)
    {
        String[] data = new String[arrayNum];
    }
    public CustomList(): this(4)
    {
    }

    public void Add (String item)
    {
        if (count > data.Length)
        {
            String[] temp = new String[count * 2];
            for (int i = 0; i < data.Length; i++)
            {
                temp[i] = data[i];
            }
            data = temp;
        }
        data[count] = item;
        count++;
    }

Solution

  • Change this:

    public CustomList(int arrayNum)
    {
        String[] data = new String[arrayNum];
    }
    

    To this:

    public CustomList(int arrayNum)
    {
        data = new String[arrayNum];
    }
    

    You have accidentally created a local variable in the constructor which is being assigned to instead of the field that you wanted to assign to.