Skip to content

Instantly share code, notes, and snippets.

@nikodemrafalski
Created August 28, 2012 10:42
Show Gist options
  • Select an option

  • Save nikodemrafalski/3497088 to your computer and use it in GitHub Desktop.

Select an option

Save nikodemrafalski/3497088 to your computer and use it in GitHub Desktop.
ILambdaEqualityComparer<T>
/// <summary>
/// Checks object of type <typeparamref name="T"/> for equality using provided delegates.
/// </summary>
/// <remarks>Use this class to avoid creating nested, narrow-scoped implementation of <see cref="IEqualityComparer{T}"/></remarks>
/// <typeparam name="T">Type that comparer will able to compare.</typeparam>
public class LambdaEqualityComparer<T> : IEqualityComparer<T>
{
private readonly Func<T, T, bool> _equalityCheck;
private readonly Func<T, int> _hashCodeProvider;
/// <summary>
/// Initializes a new instance of the <see cref="LambdaEqualityComparer{T}"/> class using
/// given <paramref name="equalityCheck"/> and <paramref name="hashCodeProvider"/>.
/// </summary>
/// <param name="equalityCheck"></param> /// <param name="hashCodeProvider"></param>
public LambdaEqualityComparer(Func<T, T, bool> equalityCheck, Func<T, int> hashCodeProvider)
{
if (equalityCheck == null)
{
throw new ArgumentNullException("equalityCheck");
}
if (hashCodeProvider == null)
{
throw new ArgumentNullException("hashCodeProvider");
}
_equalityCheck = equalityCheck;
_hashCodeProvider = hashCodeProvider;
}
/// <summary>
/// Determines whether the specified objects are equal.
/// </summary>
/// <returns>
/// true if the specified objects are equal; otherwise, false.
/// </returns>
/// <param name="x">The first object of type <typeparamref name="T"/> to compare.</param>
/// <param name="y">The second object of type <typeparamref name="T"/> to compare.</param>
public bool Equals(T x, T y)
{
return _equalityCheck(x, y);
}
/// <summary>
/// Returns a hash code for the specified object.
/// </summary>
/// <returns>
/// A hash code for the specified object.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object"/> for which a hash code is to be returned.</param>
/// <exception cref="T:System.ArgumentNullException">
/// The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null.</exception>
public int GetHashCode(T obj)
{
if (!typeof(T).IsValueType && obj == null)
{
throw new ArgumentNullException("obj");
}
return _hashCodeProvider(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment