Junting Zhu
Junting Zhu

Reputation: 131

List of self-defined class

Hi I have a question about how to List.

I am trying to define a list by

List<periodrecord> pl=new List<periodrecord>(4);

Then I wish to add items to the list via a for loop

When I did this:

for (i = 1; i < 100; i++)
        {
            try
            {
                periodrecord pr = new periodrecord();

                /*some random lines*/

                pl.Add(pr);


            }
            catch (Exception e)
            {  break; }
        }

My question is: The address of pr declared in each loop will be stored by the list. But since the pr variable itself ceases to be used by the program, will these locations be regarded as empty and somehow be overwritten? Thanks.

Considering the answer, there are still some doubts, my full codes are as follows:

   List<periodrecord> pl=new List<periodrecord>(4);
   for (i = 1; i < 100; i++)
        {
            try
            {
                periodrecord pr = new periodrecord();
                record2 = sr.ReadLine();

                SNorPartCode = record1.Split('&')[0];
                phototype = int.Parse(record1.Split('&')[1]);
                System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
                time = record1.Split('&')[2];
                pr.start = DateTime.Parse(time,provider);
                pr.SNorPartCode = SNorPartCode;
                pr.phototype = phototype;
                if (record2 != null)
                {
                    pr.end = DateTime.Parse(record2.Split('&')[2], provider);
                }
                else
                {
                    pr.end = DateTime.MaxValue;

                }
                pl.Add(pr);
                record1 = record2;

            }
            catch (Exception e)
            {  break; }
        }   

When I took the line : periodrecord pr = new periodrecord();

out from the for loop, the lines

pr.start=...
pr.end=....

altered all the items in the list.

Upvotes: 4

Views: 350

Answers (2)

p e p
p e p

Reputation: 6674

Great answer above (of course, by Jon Skeet - I can't compete with it). But it sounds to me like your basic question is about how memory is managed in C#. Memory is managed automatically in C#, the garbage collector automatically takes care of freeing up references to objects sometime after they go out of scope - i.e. in each iteration of the for loop in the case of the object pr. However, the garbage collector will still know that the reference is still in use by the list, therefore it would never deallocate that until sometime after the list itself goes out of scope.

Regarding the updated question: when pr is inside the loop, you are adding to the list the value of pr which is a reference to that object. Every time you hit the loop, that will be a different reference as you are creating a new object. However, when pr is outside of the loop, every time you add to the list you would be adding to the list the value of pr (which is the reference), only this time the value is the same regardless of the iteration. So now every item on your list contains a reference to the same object, and every single item will reflect any changes to that reference. If you change the item at index 5, or 17, or 97, or any other index in the list, all items as well as pr itself will be modified since the value of all of these is the same object reference.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502486

The address of pr declared in each loop will be stored by the list.

No, it won't. The value of the pr variable at the point at which Add is called will be stored in the list. That value is a reference - a reference to the new object you've created.

It's important to understand that the value of a variable in C# is never an object. It's always either a value type value, or a reference. Once you get your head round that - and start being very clear about the differences between variables, their values, references, and objects - a lot of things (parameter passing, assignment, garbage collection etc) become much clearer.

For example, consider:

Button x = new Button();
Button y = x;

There's only one object here - the Button created on the first line. There are two variables (x and y) and after the second line they both have the same value (a reference to that object) because of the assignment. They're still independent variables though (assigning a new value to x won't change y). Think about how that is applied to your example - you're calling pl.Add(pr) which just passes the value of pr to the Add method. After that, the pr variable is completely irrelevant as far as the list is concerned. So you could have:

pl.Add(pr);
pr = null;

and the second line wouldn't affect the list at all.

Upvotes: 16

Related Questions