Home  |  FAQ  |  About  |  Contact  |  View Source   
 
SEARCH:
 
BROWSE:
    My Hood
Edit My Info
View Events
Read Tutorials
Training Modules
View Presentations
Download Tools
Scan News
Get Jobs
Message Forums
School Forums
Member Directory
   
CONTRIBUTE:
    Sign me up!
Post an Event
Submit Tutorials
Upload Tools
Link News
Post Jobs
   
   
Home >  Tutorials >  C# >  Writing Your Own Type-Safe Collection
Add to MyHood
   Writing Your Own Type-Safe Collection   [ printer friendly ]
Stats
  Rating: 4.58 out of 5 by 38 users
  Submitted: 01/06/02
Andrew Ma ()

 
Collections are great. You can add and remove any objects without worrying about the size of the list. But what happens when you want to restrict what kind of objects go into the collection? You create a type-safe collection class.
Why would you want to do this? If you are creating your own class, let's say a list of people objects to be processed by a database, you wouldn't want someone adding an XmlNode object into your collection. I'll outline some simple instructions on how to create your own type-safe collection using the System.Collections.CollectionBase class.

We'll start with some sample code and I'll explain the sections and what's important to remember when creating your own collection.
using System;

public class People
{
    public string FirstName;
    public string LastName;
}

public class PeopleCollection : CollectionBase
{
    public void Add(People _people)
    { 
        List.Add(_people);
    }

    public void Remove(int index) 
    {
        if ((index > (Count - 1)) || (index < 0))
            throw (new Exception("Index not for PeopleCollection valid!"));
        List.RemoveAt(index);
    }

    public virtual People this[int index]
    {
        get 
        { 
            return (People) this.List[index]; 
        }
    }
}

Looks pretty simple, doesn't it?

People Class
This is the object you want to create a collection for. In this example, I've created People class which just contains a first name and a last name. We're going to restrict our new collection to only accept People objects.

PeopleCollection Class
First, let's look at the class signature. We'll notice that we're inheriting the CollectionBase class. "This base class is provided to make it easier for implementers to create a strongly typed custom collection. Implementers should extend this base class instead of creating their own" (MSDN Documentation). This is a "must do" when creating your own collection.

Add/Remove Methods
In our new collection, we have the two basic commands everyone will want in their collection. Add will take a People object as a parameter and insert it into the List (which is part of the CollectionBase class). Since the Add method only accepts People objects, this is how the collection will restrict other objects from being added since the List object is not exposed.
The Remove function takes an index as a parameter and removes the object associated with that index from the list. In our code, we've added some checking to make sure that the index exists and to throw an exception if the index is not valid. This remove method is only one way of doing it. It's also possible for a Remove method to be created based on first name or last name, or some other property of your class. Some people may even omit the remove method if they desire to do so.

Default Indexer
Now that we can add and remove people object from our collection, we need a way to access the information. We implement a default indexer so that in our code, we can access the objects of our collection like this:
PeopleCollection myPeople = new PeopleCollection();
myPeople.Add(new People());
MessageBox.Show(myPeople[0].FirstName);

The last line of that code shows us an example of the indexer in use. It's getting the first name of the 4th person in our list (the indices start with 0).
Again, just like the remove method, we can implement the indexer to return a People object based on first name (instead of index).

Other methods you can use
Although this tutorial only shows you a collection with an add method, a remove method and a default indexer, you can add more methods to help you code. Some of the collections I've written provide me a method to access the last object in the collection or the first object in the collection. The code would be like this:
public People LastPerson
{
    get 
    { 
        return (People) this.List[this.List.Count - 1]; 
    }
}


We've now completed this tutorial. These are the simple steps for creating your own type-safe collection. Hope this tutorial helps!

Tips
  • Don't forget to the "using System.Collections" line or you'll have to specify the full System.Collections.CollectionBase class name.
  • Its recommended that you put the post-fix "Collection" at the end of your collection name.
  • In your remove function, make sure the index exists.
    Links
    Devhood C# Message Forum - Feel free to ask questions to me or other Devhood members.
    http://www.devhood.com - Can't forget to mention this great resource. :-)
    - From MSDN.

    Copyright © 2001 Andrew Ma.

  • Return to Browsing Tutorials

    Email this Tutorial to a Friend

    Rate this Content:  
    low quality  1 2 3 4 5  high quality

    Reader's Comments Post a Comment
     
    Very Nice...
    -- David Cyrille, January 08, 2002
     
    Regarding the indexer, I know that C# supports indexing but other languages (like VB.NET) require the Item[index] (or other name). The following code snippit it apparently how you do it in C#:

    ...
    <IndexerName("Person")>
    public People this[int index] {...}
    ...

    Then, C# you could access a person with:
    People person = myPeople[1];

    And in VB.NET you could access a person with:
    Dim person As People = myPeople.Person(1)
    -- Heath Stewart, January 14, 2002
     
    I made a dump mistake on my previous post. Instead of "<...>", use "[...]" in C#. "<...>" is for VB.NET. Sorry.
    -- Heath Stewart, January 14, 2002
     
    shameless 1pt. comment
    -- shizo mcizo, January 15, 2002
     
    This is helpful, thx.
    -- jingmin wei, January 15, 2002
     
    This is a very informative tutorial on a type-safe collection.
    -- Ricardo Siu, January 17, 2002
     
    nice..
    -- Vincent Chan, January 21, 2002
     
    hm, looks like another ArrayList
    -- Ben Ratzlaff, January 25, 2002
     
    Ben, I don't think you quite get it. An ArrayList extends ICollection, yes, but the idea of this tutorial was a type-safe collection. ArrayLists can take any object. Type-safe collection provide the developer with a good way of making sure that only a particular type of object goes into a collection, making method calls and property access easier since you don't have to guess at what type of object you're dealing with. There's also more benefits to a type-safe collection, just as their benefits to an ArrayList. They similar, but not the same.
    -- Heath Stewart, January 26, 2002
     
    Nice tutorial man.
    -- Krishnan Subramanian, January 29, 2002
     
    Good help in C
    -- Dharmang Shelat, January 30, 2002
     
    A quality tutorial.
    -- Brian Simoneau, February 22, 2002
     
    very nice!
    -- Kuniaki Tran, March 03, 2002
     
    Some good ideas, especially since type-safety helps prevent runtime errors by erroneous user-casts.

    Readers should keep in mind that generics are on their way, in the world of .NET, which would allow you to get typesafe versions of collections without writing ANY additional code.

    Take ArrayList for example, if you have a generic ArrayList that contains type "T" (some class or interface), then the type declaration would be ArrayList<T> for the generic type. If you wanted to contain just an ArrayList of strings then, you could write ArrayList<string>, and the compiler would do all the type checking for you at that point.

    Generics have been around for a while, in other languages as C++ templates, or in some obscure Early-Access versions of Java (will also make it out for Java 1.5, I believe). Keep your eyes out for .NET generics though, if you're concerned about this issue :-)
    -- Theo Yaung, August 12, 2003
     
    Copyright © 2001 DevHood® All Rights Reserved