I want to have an object that takes a course that a student has completed, but the student can take a course 3 times if they did not pass on their first attempt, basically an array of arrays, for example:
["F", "A", " "]//This means that the student took the course twice because they failed on the first attempt and because they passed on their second, the third string remains null
This is how I initialized the "CompletedCourses" variable in the Student class
public string[,,] CompletedCourses
And this is the constructor
public Student(string StudentID, string Name, string Status, Enum StudentMajor, string[,,] CompletedCourses)
{
this.StudentID = StudentID;
this.Name = Name;
this.Status = Status;
this.StudentMajor = StudentMajor;
this.CompletedCourses = CompletedCourses;
}
This is what the object is supposed to achieve.
Student student = new("00069110", "Erling Haaland", "Full-time", Majors.Computer_Information_Systems, new string[,,]//These are the courses completed and grade(s) achieved in them.
{
{{"CS50"},{"F", "B ", " "}},
{{"Psychology 101"}, {"A", " ", " "} }//This is my idea of storing the courses a student has completed and the grade(s) they received in the courses.
});
The code above, I don't believe is the correct syntax for a multi-dimensional array, but I think it can be a guide to what the expected outcome is.
CodePudding user response:
The immediate reason your code doesn't work is because multidimensional arrays in C# require that all dimensions have the same length. You can't have both a length 1 array {"CS50"}
and a length 3 array {"F", "B ", " "}
in the same dimension. It has nothing to do with static initialisers, really.
Since you just want a collection of courses and their grades, you can create types to model those things:
enum Grade {
NotTaken, // could also be modelled with null instead, if you use Grade?
Fail,
A,
B,
C,
D,
E
}
record CompletedCourse(string name, Grade[] grades);
Then the constructor of Student
could take a List<CompletedCourse>
. Example usage:
Console.WriteLine(new Student( // omitting other arguments of the Student constructor
new() {
new("CS50", new[] { Grade.Fail, Grade.B, Grade.NotTaken }),
new("Psychology 101", new[] { Grade.A, Grade.NotTaken, Grade.NotTaken }),
}
));
Alternatively, if you want to easily search a course's grades by the course name, you can use a Dictionary<string, Grade[]>
instead, in which case the inline initialisation would look like this:
Console.WriteLine(new Student(
new() {
{ "CS50", new[] { Grade.Fail, Grade.B, Grade.NotTaken } },
{ "Psychology 101", new[] { Grade.A, Grade.NotTaken, Grade.NotTaken } },
}
));