简体   繁体   中英

c# unhandled exception: object reference not set to an instance of an object

I have a problem with an array of classes. basically I create an array of the class 'Student', but I cannot assign values to any properties of the instances in the array because I get the unhandled exception in the title. here's the code:

class ControllerQueue
{
    model.ModelStudent q = new model.ModelStudent();

    static int capacity = 15;
    model.ModelStudent[] arr = new model.ModelStudent[capacity];
    int top = -1, rear = 0;

    public ControllerQueue()
    {
        arr[0].name = "a";
        arr[0].grade = 0;
    }
}

I tried assigning values out of the constructor, but I still get the same result. now, the exception itself obviously sais I didn't instantiate the Student class but I don't understand why it would say that, I've already instantiated it. thanks in advance.

You need

arr[0] = new ModelStudent();
arr[0].name = "a";
arr[0].grade = 0;

You need this because you have to new up an instance to put into the array at index 0

model.ModelStudent[] arr = new model.ModelStudent[capacity];

Will just allocate the array, but each entry is by default the default value of ModelStudent (null)

you need to instantiate the members of your array

add the item to your array like this

arr[0] = new ModelStudent();
arr[0].name = "a";
arr[0].grade = 0;

Your item 0 is not set.

Try.

model.ModelStudent q = new model.ModelStudent();

        static int capacity = 15;
        model.ModelStudent[] arr = new model.ModelStudent[capacity];
        int top = -1, rear = 0;


        public ControllerQueue()
        {
            arr[0] = new model.ModelStudent();
            arr[0].name = "a";
            arr[0].grade = 0;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM