I have written a program that is supposed to get a list of names and information. Well, I got to solve this question a few classes, such as students and university have to answer. But the problem is where I plan to get students information
static void Main(string[] args) {
Console.WriteLine("Some students enter the information you want? ");
Cunt = int.Parse(Console.ReadLine());
University university = new University();
university.Add();
university.Sort();
university.Report();
Console.ReadKey();
}
To solve this problem, I have to specify the number of students .
class University { Student[] student = new Student[3];
private int n = 0;
public University()
{
for (int i = 0; i < 3; i++)
student[i] = new Student();
}
public void Add()
{
Console.WriteLine();
for (int i = 0; i < 3; i++)
{
student[n].Read();
n++;
}
}
For example, the number of students I have three. How do I create a way to enter the number of students who give information and do not default؟Instead of the number 3 is a variable that give the user the desired number.
Then change the program with help from friends, but I got this problem.
class University
{
// Student[] student = new Student[3];
public int NumbersOfStudents { get; private set; }
public Student[] student;
public University(int numberOfStudents)
{
for (int i = 0; i < numberOfStudents; i++)
student[i] = new Student();
}
private int n = 0;
/* public University()
{
for (int i = 0; i < 3; i++)
student[i] = new Student();
}*/
But when I run it I get the error: Object reference not set to an instance of an object.
notic:The program can not I use the list.
You're never initializing your student
field, so it's null. You could use:
// Note: public fields are almost *always* a bad idea
private readonly Student[] students;
public University(int numberOfStudents)
{
students = new Student[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++)
{
students[i] = new Student();
}
}
However, that's a pretty nasty solution, in my view - why are you creating all these useless Student
objects? Why are you populating the University
ahead of time?
It would be better to use List<T>
rather than an array:
public class University
{
private readonly IList<Student> students = new List<Student>();
// Presumably some other fields and properties
public void AddStudent(Student student)
{
students.Add(student);
}
}
See more on this question at Stackoverflow