Tuesday, April 15, 2008

KeyedCollection class

If you follow a entity object based design in your applications you frequently need to maintain lists of your objects. You can use List<T> class to do that. I was using the same method until I ran code analysis on one of the projects and got the warning  for violating rule "CA1002:DoNotExposeGenericLists". The following blog post explains the background behind the rule http://blogs.msdn.com/fxcop/archive/2006/04/27/585476.aspx

A better alternative is to use the KeyedCollection <TKey, TItem> class. As the documentation states it provides an abstract base class for a collection whose keys are embedded in the values. For example you can have an Employee class that has the key EmployeeNumber as a field. In this example you want to be able to do operations on your collection class (lets say EmpleyeeCollection) based on the employee number. Since the KeyedCollection class has to know how to get a key from an item it is an abstract class. You have to derive your own class and override the GetKeyForItem method. The following blog post has a clever method to avoid creating a collection class for every object that utilizes lambda expressions http://vaultofthoughts.net/keyedcollectionlambdaexpressionway.aspx

No comments: