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.