ConcurrentHashSet icon indicating copy to clipboard operation
ConcurrentHashSet copied to clipboard

Feature request: Add another overload of `Add` with an `out` parameter to return existing item if already in set

Open extremeandy opened this issue 4 years ago • 0 comments

I often use ConcurrentDictionary as a way to force a single instance of a reference typed object.

e.g.

var dict = new ConcurrentDictionary<MyClass, MyClass>();
var item1 = new MyClass();
var resultItem1 = dict.GetOrAdd(item1, item1);

var item2 = new MyClass();
var resultItem2 = dict.GetOrAdd(item2, item2);

Assert.Same(item1, resultItem2); // Expect reference equality to the first item that was added

I would prefer to use your ConcurrentHashSet, but I need an atomic way to both add and retrieve an item. Otherwise, I have to make two calls - one to add, and one to retrieve, so performance wise I'm better off sticking with ConcurrentDictionary.

Could we add another overload of Add which has an out T parameter to allow the item that is in the set after the Add operation to be returned?

extremeandy avatar Aug 13 '21 05:08 extremeandy