Alex Rivera | Logout

add elements to object array

Asked 2011-04-23T17:36:26.113
30

This must be really simple but just not getting my syntax right here. let's say we have classes like two below:

class Student
{
    Subject[] subjects;
}

class Subject
{
    string Name;
    string referenceBook;
}

Here is my code:

Student univStudent = new Student();

Now, I want to add subjects here but not able to do something like

univStudent.subjects.add(new Subject{....});

How do i add items to this object array?

Edit
Report

1 Answer

71

You can try

Subject[] subjects = new Subject[2];
subjects[0] = new Subject{....};
subjects[1] = new Subject{....};

alternatively you can use List

List<Subject> subjects = new List<Subject>();
subjects.Add(new Subject{....});
subjects.Add(new Subject{....});
// Then you can convert the List to Array like below:
Subject[] arraySubjects = subjects.ToArray<Subject>() 
answered 2011-04-23T17:39:51.517

Your Answer