Collections should implement generic interface TypeName: | CollectionsShouldImplementGenericInterface | CheckId: | CA1010 | Category: | Microsoft.Design | Message Level: | Error | Certainty: | 90% | Breaking Change: | NonBreaking |
Cause: An externally visible type implements the System.Collections.IEnumerable interface but does not implement the System.Collections.Generic.IEnumerable<T> interface, and the containing assembly targets .NET Framework version 2.0. This rule ignores types that implement System.Collections.IDictionary.
Rule Description To broaden the usability of a collection, implement one of the generic collection interfaces. Then the collection can be used to populate generic collection types such as the following: How to Fix Violations To fix a violation of this rule, implement one of the following generic collection interfaces: When to Exclude Messages It is safe to exclude a message from this rule; however, the collection will have a more limited use. Example Code The following example shows a collection, IntegerCollection, that violates the rule. In GenericIntegerCollection, the collection is modified to satisfy the rule by implementing System.Collections.Generic.IEnumerable<T>. Finally, the collection is used to populate a strongly typed stack. [C#] using System; using System.Collections; using System.Collections.Generic;
namespace DesignLibrary { // This class violates the rule. public class IntegerCollection: CollectionBase { // Methods overrides using Int32. }
// This class satisfies the rule. public class GenericIntegerCollection: CollectionBase, IEnumerable<int> { public int Add(int value) { return InnerList.Add(value); }
// Other method overrides using Int32.
public new IEnumerator<int> GetEnumerator() { foreach (int data in InnerList) { yield return data; } } }
class Test { static void Main() { IntegerCollection intCollection = new IntegerCollection();
// The following line would generate a compiler error. //Stack<int> integerStack = new Stack<int>(intCollection);
GenericIntegerCollection genericIntCollection = new GenericIntegerCollection(); genericIntCollection.Add(2); genericIntCollection.Add(4);
Stack<int> integerStack = new Stack<int>(genericIntCollection); Console.WriteLine(integerStack.Pop()); Console.WriteLine(integerStack.Pop()); } } } Related Rules Avoid excessive parameters on generic types Do not declare static members on generic types Do not expose generic lists Do not nest generic types in member signatures Generic methods should provide type parameter Use generic event handler instances Use generics where appropriate See Also Generics DesignGuidelines |