Is this good practice : Adding object to a List<T> | Sololearn: Learn to code for FREE!
+ 2

Is this good practice : Adding object to a List<T>

I have a custom object : Student To fill my studentlist with Students I use a loop for (int i = 0; i < 10; i++) { Console.WriteLine(i); NewStudent.Name = Names[i]; StudentList.Add(NewStudent); //Add student to the list NewStudent = new Student(); //Create a new student object for the next student } https://code.sololearn.com/cn0ASzGoDHJN After adding the student I create a new student object for the next student. I am afraid this is causing a memory leak, but my code works fine. Is this a good way to do this ?

18th Jan 2019, 8:48 PM
sneeze
sneeze - avatar
2 Answers
+ 2
What if you need to add more data to student. for (int i = 0; i < 10; i++) { Console.WriteLine(i); StudentList.Add(new Student { Name = Names[i] }); } And it does not fit one line. 1) make private variables and fill those. Still use one line to add the student 2) Get the last added student object from the collection and add the data to the object ?
18th Jan 2019, 9:25 PM
sneeze
sneeze - avatar
+ 1
Thanks man. You did it again. Now it makes sense with every object having it own memory. Just need to get used to doing more than one thing on a line.
18th Jan 2019, 9:11 PM
sneeze
sneeze - avatar