Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft.Maintainability Error with List Extension Methods

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.

like image 427
Ian Dallas Avatar asked Mar 11 '26 10:03

Ian Dallas


2 Answers

I think your code triggered a bug in FxCop, "Collection was modified" is a classic oops. It then decided that its bug was your problem, catch(Exception) style.

Look for an update. The one I use doesn't complain about your code (VS2010 version).

like image 99
Hans Passant Avatar answered Mar 13 '26 23:03

Hans Passant


It's telling you that you are changing the list as you are enumerating it. This is clear from your code (you're adding to the list at the same time as enumerating).

How about:

public static void UniqueAddRange<T>(this List<T> list, IEnumerable<T> values)
{
    list.AddRange(values.Except(list));
}

Or, if the interface is right for your needs, use a Hashset. It does what you want out of the box.

like image 36
spender Avatar answered Mar 14 '26 00:03

spender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!