0

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++;
    }

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Change your code.

Your data object in constructor is local variable. And you are not initializing your instance data object.

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

public int Count
{
    get { return count; }
}
public CustomList(int arrayNum)
{
     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++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.