Hire my services

If you would like to hire my services, you can now do so by visiting the following link:

Website Design Darlington

Article Statistics

ArticlesLatest Entry
2121-May-2008

Code Bank Statistics

CategoryTipsLatest Entry
Applications420-Feb-2008
Cache118-Apr-2007
Controls926-Jul-2007
CSS107-Sep-2007
Database428-Aug-2007
Dates128-Aug-2007
Email105-Mar-2007
Files123-Apr-2007
HTML101-Mar-2007
Images226-Mar-2007
Pages115-Oct-2007
Sessions122-Nov-2007
SQL Server1518-Mar-2008
Strings309-May-2007
Skip Navigation LinksHome > Articles > Using Generics to create a property list

Using Generics to create a property list

Summary: An example of how the System.Collections.Generic namespace can allow us to create a Property which can be added to, referred to by index and also iterated.Socialize it

I recently came across a situation where I wanted to add a list of objects to a class and then refer to them by index. The System.Collections.Generic namespace came to the rescue, specifically via it's List Generic class.

To demonstrate the situation, imagine we have a box which can contain multiple files. Firstly, I'd need to create a box class (perhaps with an ID so that we can reference it later) and then I'd need a Files property to which I could add multiple files. I'll also have to create a File class which I'll add an ID to as well.

To represent this in code, we would create a File class with one property for the ID e.g.

Then, we need to look at how we create our Box class and this is where the Generics come in. Unlike our File class above, we need to be able to create a list of files rather than just one variable such as the ID. To do this, we can use the List class and the IList interface. When we create our Files property we need to tell it that it is actually a list and also what the list contains. In this case it will contain a list of our Files class e.g.

Now, if I want to create a new box and add some files to it, I can do so very easily like this:

Also, if I need to go back and reference a file by it's index I can do so like this:

And, if needed, I can loop through the entire list of files:

Reader Comments

1. Chris Davis 18/05/2007 02:44:04

2. Will Asrari 13/06/2007 19:58:38

3. Jeff 13/07/2007 13:48:23

Add your comments

Please keep your comments relevant to this page. Any inappropriate or purely promotional comments may be removed. Email addresses are never displayed but are required so you can confirm your comments.

Your Name:
 
Your Email:
 
Add your comments: