-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnonymousEqualityComparer.cs
38 lines (33 loc) · 1.36 KB
/
AnonymousEqualityComparer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
namespace Recore.Collections.Generic
{
/// <summary>
/// Compares instances of a type using the given equality function.
/// </summary>
/// <remarks>
/// Note that there is no corresponding <c>AnonymousComparer<T></c> type for <see cref="IComparer{T}"/>.
/// That use case is already filled by <see cref="Comparer{T}.Create(Comparison{T})"/>.
/// </remarks>
public sealed class AnonymousEqualityComparer<T> : IEqualityComparer<T?>
{
private readonly Func<T?, T?, bool> equals;
private readonly Func<T, int> getHashCode;
/// <summary>
/// Creates an instance of <see cref="AnonymousEqualityComparer{T}"/>.
/// </summary>
public AnonymousEqualityComparer(Func<T?, T?, bool> equals, Func<T, int> getHashCode)
{
this.equals = equals ?? throw new ArgumentNullException(nameof(equals));
this.getHashCode = getHashCode ?? throw new ArgumentNullException(nameof(getHashCode));
}
/// <summary>
/// Invokes the given comparison function on two objects.
/// </summary>
public bool Equals(T? x, T? y) => equals(x, y);
/// <summary>
/// Invokes the given hashing function on an object.
/// </summary>
public int GetHashCode(T obj) => getHashCode(obj);
}
}