Skip Navigation LinksHome > Categories > Code from a Category

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.



User Name: codelecturer
Name: Mike Chauhan
Contact Me: www.datawebcoder.com/ContactUs.aspx
Home Page: www.datawebcoder.com
6 years of total IT experience including programming, application development, System Maintenance . 3 years of Experienced and expertise in .Net Framework VB, Visual Basic.Net, ASP.Net 2.0, 3.5 and AD... [More]
Viewed Times: 1691
Add Date: 11/13/2011
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.
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:

Post a Comment

Name: (Optional)
Email: (Optional, you can get an email if somebody replys your comments)*
Email me if somebody respons my comment below:
Details**:
Enter Text
as Below:
(case insensitive, if hard to read, click the "get a new one" button)
 
    
* Your email address will not be shared with any third parties for any reason.
** Maximum 1000 charactors.