Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix behavior ObjectCollection for single item contains
  • Loading branch information
hoyosjs committed Sep 23, 2021
commit d71f44276af2b6d0bc427f6c1bc7368c0769bbf2
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,9 @@ public void Clear()
}

public bool Contains(T item) =>
ReferenceEquals(item, _items) ||
(_size != 0 && _items is T[] items && Array.IndexOf(items, item, 0, _size) != -1);
_size == 0 || _items is null ? false :
_items is T o ? o.Equals(item) :
_items is T[] items && Array.IndexOf(items, item, 0, _size) != -1;

public void CopyTo(T[] array, int arrayIndex)
{
Expand All @@ -120,7 +121,7 @@ public void CopyTo(T[] array, int arrayIndex)

public bool Remove(T item)
{
if (ReferenceEquals(_items, item))
if (_items is T o && o.Equals(item))
{
_items = null;
_size = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,29 @@ public void Ctor_ExecuteBothOverloads_MatchExpectation()
c.Add("value1");

Assert.Throws<InvalidOperationException>(() => { c.Add(null); });
}

[Fact]
public void ContainsAndRemove_UsesEqualitySemantics()
{
// Use default validator
ObjectCollection<string> c = new ObjectCollection<string>();

Assert.Equal(0, c.Count);
Assert.False(c.Contains("value" + 1));

c.Add("value" + 1);

Assert.Equal(1, c.Count);
Assert.True(c.Contains("value1"));
// Force the reference to be different to ensure we are checking for semantic equality
// and not reference equality.
Assert.True(c.Contains("value" + 1));
c.Add("value" + 2);

Assert.True(c.Remove("value" + 1));
Assert.Equal(1, c.Count);

Assert.True(c.Contains("value" + 2));
}
}
}