Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add elements to object array

Tags:

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?

like image 738
user583126 Avatar asked Apr 23 '11 17:04

user583126


People also ask

How do you add properties to an array of objects?

We can use the forEach method to loop through each element in an object and add a property to each. We have the arr array. Then we call forEach with a callback that has the element parameter with the object being iterated through and we assign the b property to a value. according to the console log.


1 Answers

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{....}); 
like image 117
Bala R Avatar answered Sep 20 '22 03:09

Bala R