views:

101

answers:

7

Following code should throw exception to prevent adding duplicate collection item.

ICollection<T> collection = new List<T>();

public void Add(T item)
{
    if (collection.Contain(item))
    {
          throw new SomeExceptoinType()
    }

    collection.Add(item);
}

What standard exception type is the most apropriate?

+1  A: 

I would use InvalidOperationException:

The exception that is thrown when a method call is invalid for the object's current state.

Since the validity of the argument's value is contingent upon the state of the object (that is whether or not collection.Contains(item) is true) I think this is the best exception to use.

Make sure that you add a good message to the exception that makes it clear what the problem was to the caller.

Andrew Hare
IMHO, InvalidOperationException will confuse user because it used mostly to show unapropriate oparation sequence. For instance, reading from closed reader, etc.
klashar
+2  A: 

ArgumentException would probably be the best. This is the exception thrown when an argument is invalid.

Brandon
+1  A: 

ArgumentException would be the proper exception (Dictionary uses that exception as well)

cyberconte
+1  A: 
System.ArgumentException
Ben M
+5  A: 

Well, Dictionary<,>.Add() throws ArgumentException if such key already exists, so I guess this could be a precedent.

Pavel Minaev
A: 

I'd say InvalidOperationException, because it is not valid to add an object that's already in the collection

Thomas Levesque
If it were a Dictionary this would be true, but it's not.
Brandon
There are collections that don't allow duplicates, AND dictionaries that allow them... in the poster's case he clearly doesn't want duplicates, or why would he want to throw an exception ?
Thomas Levesque
Sorry, I phrased that comment badly, I more meant to say that if the OP is using a collection that does allow duplicates, its not really an invalid operation. Its a "he doesn't consider this valid" thing. Also I'm not the one who downvoted this >_> I don't agree this is the best exception, but I don't think it would be wrong to use it.
Brandon
+1  A: 

I would throw an ArgumentException. That's what the generic System.Collections.Generic.SortedList<> does in its Add method.

From the .NET Framework 2.0 code:

    public void Add(TKey key, TValue value)
    {
        if (key == null)
        {
            System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.key);
        }
        int num = Array.BinarySearch<TKey>(this.keys, 0, this._size, key, this.comparer);
        if (num >= 0)
        {
            System.ThrowHelper.ThrowArgumentException(System.ExceptionResource.Argument_AddingDuplicate);
        }
        this.Insert(~num, key, value);
    }
Paul Williams