How to avoid Code Analysis CA1002

I recently made some code like this:
public class MenuItem
{
private List _subItems;

public List SubItems
{
get { return _subItems;}
}

… …
}

This caused Code Analysis to throw a CA1002 warning – Do not expose generic lists.
(see ms help: http://msdn2.microsoft.com/en-us/library/ms182142(VS.90).aspx)

The help didn’t help much, but i solved it pretty simply by making a class that inherits the List generic class:

public class MenuItemCollection : List
{
}

public class MenuItem
{
private MenuItemCollection _subItems;

public MenuItemCollection SubItems
{
get { return _subItems;}
}

… …
}

This will avoid the CA1002 warning. Remember to name the collection class “Collection” in the end. Otherwise you will get a CA1710 warning, Identifies should have correct suffix. (http://msdn2.microsoft.com/en-us/library/ms182244(VS.90).aspx)

Comments

2 responses to “How to avoid Code Analysis CA1002”

  1. jlembke Avatar

    The only problem is, the intent of Code Analysis is to help you build better code. Don’t view fxCop/Code Analysis as a hurdle to overcome, but rather as a teaching tool. Your solution works, but it circumvents the intent of the rule. The writers of the rule say: “[List(T)] is designed to be used in internal implementations and are optimized for performance and power at the cost of cleanness and flexibility. If you return List(T), you will not ever be able to receive nitifications when client code modifies the collection. Also, List(T) exposes many members, like BinarySearch, that are not useful or applicable in many scenarios” – Framework Design Guidelines -Cwalina and Abrams.

    Best,
    Jeff

  2. jlembke Avatar

    The only problem is, the intent of Code Analysis is to help you build better code. Don’t view fxCop/Code Analysis as a hurdle to overcome, but rather as a teaching tool. Your solution works, but it circumvents the intent of the rule. The writers of the rule say: “[List(T)] is designed to be used in internal implementations and are optimized for performance and power at the cost of cleanness and flexibility. If you return List(T), you will not ever be able to receive nitifications when client code modifies the collection. Also, List(T) exposes many members, like BinarySearch, that are not useful or applicable in many scenarios” – Framework Design Guidelines -Cwalina and Abrams.

    Best,
    Jeff

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.