Adding object

Toch

New member
Joined
Apr 22, 2015
Messages
2
Programming Experience
Beginner
Hi,

I'm a new C# Developer Community user and I'm also a beginner C# programmer. I have the following C # code:
 // I create an array of five students from a Student class 
   Student[] myStudents = new Student[5];

 // I create a class object named Biology from the Course class 
      Course cs = new Course();
      cs.courseName = "Biology";

Now I would like to know how to add my first student to the course object(cs) please. I tried myStudents[0].add(cs), myStudents[0].Add(cs), I tried everything but nothing ever worked.

Thank you in advance for your valuable support.
 
How are your Student and Course classes defined? You can't "add" one object to another without the second object being designed to support that. In your case, it makes sense to add a Student to a Course, so I'd suggest that your Course class should be defined something like this:
public class Course
{
    private List<Student>_students = new List<Student>();

    public List<Student> Students
    {
        get
        {
            return _students;
        }
    }

    // ...

}
You can then do things like this:
myCourse.Students.Add(myStudent);
 
The problem, this is an assignment and I have follow the instructions that mentioned I have to create arrays of size 5 for students, instantiate them, instantiate a Biology Course object then add my five students to the Biology Course object. If I find the solution for the first, I can do it for the others. I do not know anything yet about List, I'm a beginner C# programmer and I want to really understand everything I'm doing. There any other way I can do it with an array ?
 
...I have to create arrays of size 5 for students, instantiate them, instantiate a Biology Course object then add my five students to the Biology Course object.

That doesn't actually make any sense. As I said, you can't "add" anything to an object that that object hasn't been designed to support. If the Course object has nowhere to specifically put a Student object or a Student array then what does "add" even mean? Can you "add" a telephone to a dog?
 
Back
Top Bottom