Posts Tagged ‘ Objects ’

Collections of Objects

A Collection is simply an object that knows how to manage references to multiple instances of other classes. It keeps track of other objects. There are different collections to choose from. Each of them with their own “powers”. Some are created to keep objects sorted, some are created to allow for easy retrieval. The use of collections is quite common in the .NET Framework Class Library.

For now I am just focusing on the list collection, because it is the most simple one. To have an example to look at, I created a little project with a button called “myButton” and a textBox called “myTextBox”. First I add a class that I can work with:

Visual Studio nicely adds my class in a new page to my project:

I want to add two properties to my class:

So, let’s go back to my MainPage.xaml.cs file and add three instances of the car class inside the click event handler:

Each instance has different properties.

Now I want to add each of these instances to a new collection, a list. Once I have them in the list I want to loop through each item in the list.

I am going to inspect the properties of each instance of a car class, adding it to a string that I then display in the textblock on the phone’s user interface:

First I created a new instance of a new collection, a list collection. This new List<Car>(), which is a Generic List, can only work with my Car class. The List Object has a number of methods for managing the objects that it holds a reference to. The “Add” method allows me to add a reference to the list. The “foreach” statement works with collections. It iterates through my list and for each car in that list it displays the Make and the Model:

 

To be continued…

Advertisements
%d bloggers like this: