....
....
Employee employeeInfo;
for(int i =0; i<n;++i)
{
employeeInfo = new Employee();
employeeInfo.FirstName = arr[i].ToString();
employeeInfo.Age = i;
employeeList.Add(employeeInfo);
....
}
views:
212answers:
6According to your code snippet:
in every iteration you create a new object and previous object, referenced by employeeInfo
will be eligible for GC.
If you don't do anything else with the employeeInfo you created then in means you are doing something useless - create objects that are not used => lost time allocating memory
Objects doesn't have names. What you have is a local variable that is a reference to an object, and the variable is used for each object that is created.
You can use the local variable to keep track of the current object, and later in the loop store the object in a collection.
If you don't store each object somewhere, the previous object will be lost when you assign the next object to the variable. The previous object still exists, but as there is no longer any reference to it, it will be removed by the garbage collector later on.
employeeInfo = new Employee();//this is where you are "instantiating objects with the same name" in your for loop.
Everytime when this loc is called, your previous value in employeeInfo object gets replaced with the initial state of the object; this means when this new is called, then properties/variables of employeeInfo shall be replaced by default values(provided by constructor, if any).
See the variable as a box. You place a new Employee() in the box, give it a name, add it to some collection. On he next iteration of the loop you place turn over the box(throwing away the reference to the previous Employee, but that doesnt matter since your collection still has the reference) and add yet a new Employee() in the box. Anything not in a box will be cleaned by the garbage collector