Lists and simple objects are each useful by themselves, but when you put them together, you get quite a bit more power than either one can give you by itself. In this section, we'll explore the possibilities that come by combining these two approaches to managing collections of data.
You already know that Lists can contain a list of values. When I introduced Lists, all of the examples involved lists of strings. But Lists can contain a list of any kind of object, not just a string. For example, you could create a List and put Point objects in it, like this:
List<Point> pointList = new List<Point>(); int i = 1; while (i < 4) { Point p = new Point(); p.x = i; p.y = i; pointList.add(p); i++; }
After the while loop, pointList contains 3 Point objects, representing the locations (1,1), (2,2), and (3,3).
Let's spend a few moments analyzing exactly how this code works. Remember that when you call a method and pass an object (like p) as a parameter, the method receives a reference to the object. Also, Lists store references to objects, rather than the objects themselves. So, after the first object is added to the method, we have this situation:
After the second object is added, the picture looks like this:
And after the third object is added, we have this:
After the loop ends, p is destroyed, but all three objects live on, because the List contains a reference to each one of them in its slots.
Now, to display the list of Points, we could write the following:
int i = 0; while (i < pointList.Count) { Point p = pointList[i]; Console.WriteLine("(" + p.x + ", " + p.y + ")"); i++; }
Each time through the loop, the following line gets the next object from the list:
Point p = pointList[i];
Since we put Point objects into the list, we must retrieve Point objects from the list. Thus, the variable p that receives the extracted value must be of type Point. It would be a mistake to try to get, say, string objects from the list, like this:
string s = pointList[i]; // NOT LEGAL
If we had this line of code in the loop, the compiler would report an error.