So I have tried to create some basic extension methods for List
. Essentially I have a UniqueAdd and UniqueAddRange. It will check for the existence of a value before adding and if its already in the List it will not add it. Here is the code:
public static class ListExtensions
{
/// <summary>
/// Adds only the values in the 'values' collection that do not already exist in the list. Uses list.Contains() to determine existence of
/// previous values.
/// </summary>
/// <param name="list"></param>
/// <param name="values"></param>
public static void UniqueAddRange<T>(this List<T> list, IEnumerable<T> values)
{
foreach (T value in values)
{
list.UniqueAdd(value);
}
}
/// <summary>
/// Adds the value to the list only if it does not already exist in the list. Uses list.Contains() to determine existence of previos values.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="value"></param>
public static void UniqueAdd<T>(this List<T> list, T value)
{
if (!list.Contains(value))
{
list.Add(value);
}
}
}
And I get the following error when building:
CA0001 : Rule=Microsoft.Maintainability#CA1506, Target=Some.Namespace.ListExtensions : Collection was modified; enumeration operation may not execute.
Here is the link to the error but I'm not sure how to fix my extension methods given this information. It says to
Try to redesign the type or method to reduce the number of types to which it is coupled.
Does anyone know why I'm getting this error and how to fix my extension methods so they do not violate this rule?
Thanks!
PS: Before anyone mentions it, I have considered using a HashSet but HashSet does not exist in the compact framework.