0

I am attempting to write a method on my array that can pass values into the class variables but I am receiving a nullreference exception error:

System.NullReferenceException: 'Object reference not set to an instance of an object.student was null.'

Here is my code for my method :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arrays_and_collections
{
    class Program
    {
        static void Main(string[] args)
        {
            int no_studs;   
            Console.WriteLine("Please enter the number of students you have : ");
            no_studs = Convert.ToInt32(Console.ReadLine());
            Student[] students = new Student[no_studs];
            int initializer = 0;
            foreach (Student student in students) {


                Console.WriteLine("Please enter the name of {0} student :", initializer + 1);
                student.Name=Convert.ToString(Console.ReadLine());
                Console.WriteLine();
                Console.WriteLine("Please enter the gpa of {0} student : ", initializer + 1);
                student.Gpa = Convert.ToDouble(Console.ReadLine());
                Console.WriteLine();
                initializer++;
            }

    }

    }

}

and here is my code for my class Student :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arrays_and_collections
{
    public class Student
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }


        private double gpa;

        public double Gpa
        {  
            get { return gpa; }
            set { gpa = value; }
        }



    }
}

I have done some research and it stated that the null reference exception happens when you are trying to reference a variable that does not have a value assigned to it and I want to ask how I can solve this method of mine . Thank you.

nTIAO
  • 273
  • 1
  • 4
  • 13
  • like almost always, you created an array of Student, but that doesn't mean you actually created the instances of them. in the start of every iteration you should declare var student = new Student(); and populate the students[i] with it. And Do not use foreach on uninitialized array, only a for loop – Orel Eraki Sep 30 '18 at 08:20
  • You created an array of Student. But this array contains nulls at first. You have to create instances of Student yourself and add it to the array. – Filip Minx Sep 30 '18 at 08:21
  • Within the accepted answer of the duplicate, see "Array Elements" – Jon Skeet Sep 30 '18 at 08:23

0 Answers0