V3224. Consider using an overload with 'IEqualityComparer', as it is present in similar cases for the same collection element type.
The analyzer has detected a method or constructor call where an argument implementing the IEqualityComparer<T>
interface is not passed. Developers may have omitted this argument by mistake. This is indicated by the presence of other methods or constructors that handle collections with elements of the same type, where the IEqualityComparer<T>
argument is passed.
The example:
class CustomObjectComparer : IEqualityComparer<CustomObject> {}
static CustomObjectComparer _comparer = new();
HashSet<CustomObject> _hashSet = new(_comparer);
Dictionary<CustomObject, int> _dictionary = new(_comparer);
List<CustomObject> _list = new();
void ExampleFoo(CustomObject obj)
{
....
if (_list.Contains(obj)) // <=
....
}
In this example, the _hashSet
and _dictionary
collections are initialized using the _comparer
constructor argument, which determines the specific logic for comparing elements in these collections.
There is another collection in the code called _list
. It cannot take _comparer
when it's initialized because there's no corresponding parameter in the constructor.
However, the ExampleFoo
method contains a call to list.Contains
. This call can take an argument that implements the IEqualityComparer<CustomObject>
interface. In this case, however, the argument is missing.
Since in other cases _comparer
is used to override the comparison logic for elements of the same type, the absence of this argument in this call looks suspicious. There may be an error here, which causes the check for the presence of the _list
element to be performed incorrectly.
The fixed code in this case may look like this:
void ExampleFoo(CustomObject obj)
{
....
if (_list.Contains(obj, _comparer))
....
}
This diagnostic is classified as: