tags:

views:

141

answers:

2

Is this kind of if-testing necessary when removing an item?

if (_items.Contains(item))
{
    _items.Remove(item);
}

And, what about this test?

if (!_items.Contains(item))
{
    _items.Add(item);
}
+11  A: 

You don't have to test to remove. Remove() will return false if it didn't remove anything.

If you don't want duplicate items in your list you can test, before adding. Otherwise, you'll have duplicates.

See also: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

Lance Fisher
If you don't want duplicates, you shouldn't test; you should use a collection that doesn't let you have duplicates. Otherwise, you don't have thread-safety.
Tordek
Assuming thread safety is an issue. If it is, you also need to be sure your collection class is thread-safe (I'm guessing MS's may be, idk).
Snarfblam
+7  A: 

You could also use a HashSet<T> if you want to be able to Add() an item multiple times and have it only exist in the collection once, without checking Contains() first.

Saxon Druce