Windows apps
Collapse the table of content
Expand the table of content
Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

EqualityComparer<T> Class

 

Provides a base class for implementations of the IEqualityComparer<T> generic interface.

Namespace:   System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)

System.Object
  System.Collections.Generic.EqualityComparer<T>

[SerializableAttribute]
public abstract class EqualityComparer<T> : IEqualityComparer, 
	IEqualityComparer<T>

Type Parameters

T

The type of objects to compare.

NameDescription
System_CAPS_protmethodEqualityComparer<T>()

Initializes a new instance of the EqualityComparer<T> class.

NameDescription
System_CAPS_pubpropertySystem_CAPS_staticDefault

Returns a default equality comparer for the type specified by the generic argument.

NameDescription
System_CAPS_pubmethodEquals(T, T)

When overridden in a derived class, determines whether two objects of type T are equal.

System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethodFinalize()

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetHashCode(T)

When overridden in a derived class, serves as a hash function for the specified object for hashing algorithms and data structures, such as a hash table.

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_protmethodMemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_pubmethodToString()

Returns a string that represents the current object.(Inherited from Object.)

NameDescription
System_CAPS_pubinterfaceSystem_CAPS_privmethodIEqualityComparer.Equals(Object, Object)

Determines whether the specified objects are equal.

System_CAPS_pubinterfaceSystem_CAPS_privmethodIEqualityComparer.GetHashCode(Object)

Returns a hash code for the specified object.

Derive from this class to provide a custom implementation of the IEqualityComparer<T> generic interface for use with collection classes such as the Dictionary<TKey, TValue> generic class, or with methods such as List<T>.Sort.

The Default property checks whether type T implements the System.IEquatable<T> generic interface and, if so, returns an EqualityComparer<T> that invokes the implementation of the IEquatable<T>.Equals method. Otherwise, it returns an EqualityComparer<T>, as provided by T.

We recommend that you derive from the EqualityComparer<T> class instead of implementing the IEqualityComparer<T> interface, because the EqualityComparer<T> class tests for equality using the IEquatable<T>.Equals method instead of the Object.Equals method. This is consistent with the Contains, IndexOf, LastIndexOf, and Remove methods of the Dictionary<TKey, TValue> class and other generic collections.

The following example creates a dictionary collection of objects of type Box with an equality comparer. Two boxes are considered equal if their dimensions are the same. It then adds the boxes to the collection.

The dictionary is recreated with an equality comparer that defines equality in a different way: Two boxes are considered equal if their volumes are the same.

using System;
using System.Collections.Generic;

class Program
{
	static Dictionary<Box, String> boxes;

	static void Main()
	{
		BoxSameDimensions boxDim = new BoxSameDimensions();
		boxes = new Dictionary<Box, string>(boxDim);

		Console.WriteLine("Boxes equality by dimensions:");
		Box redBox = new Box(8, 4, 8);
		Box greenBox = new Box(8, 6, 8);
		Box blueBox = new Box(8, 4, 8);
		Box yellowBox = new Box(8, 8, 8); 
		AddBox(redBox, "red");
		AddBox(greenBox, "green");
		AddBox(blueBox, "blue");
		AddBox(yellowBox, "yellow");

		Console.WriteLine();
		Console.WriteLine("Boxes equality by volume:");

		BoxSameVolume boxVolume = new BoxSameVolume();
		boxes = new Dictionary<Box, string>(boxVolume);
		Box pinkBox = new Box(8, 4, 8);
		Box orangeBox = new Box(8, 6, 8);
		Box purpleBox = new Box(4, 8, 8);
		Box brownBox = new Box(8, 8, 4);
		AddBox(pinkBox, "pink");
		AddBox(orangeBox, "orange");
		AddBox(purpleBox, "purple");
		AddBox(brownBox, "brown");
	}

	public static void AddBox(Box bx, string name)
	{
		try
		{
			boxes.Add(bx, name);
			Console.WriteLine("Added {0}, Count = {1}, HashCode = {2}", 
				name, boxes.Count.ToString(), bx.GetHashCode());
		}
		catch (ArgumentException)
		{
			Console.WriteLine("A box equal to {0} is already in the collection.", name);
		}
	}
}

public class Box
{
	public Box(int h, int l, int w)
	{
		this.Height = h;
		this.Length = l;
		this.Width = w;
	}
	public int Height { get; set; }
	public int Length { get; set; }
	public int Width { get; set; }
}

class BoxSameDimensions : EqualityComparer<Box>
{
	public override bool Equals(Box b1, Box b2)
	{
		if (b1 == null && b2 == null)
         return true;
      else if (b1 == null || b2 == null)
         return false;

		if (b1.Height == b2.Height && b1.Length == b2.Length
							&& b1.Width == b2.Width)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	public override int GetHashCode(Box bx)
	{
		int hCode = bx.Height ^ bx.Length ^ bx.Width;
		return hCode.GetHashCode();
	}

}

class BoxSameVolume : EqualityComparer<Box>
{
	public override bool Equals(Box b1, Box b2)
	{
		if (b1 == null && b2 == null)
         return true;
      else if (b1 == null || b2 == null)
         return false;

      if (b1.Height * b1.Width * b1.Length == 
			b2.Height * b2.Width * b2.Length)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	public override int GetHashCode(Box bx)
	{
		int hCode = bx.Height * bx.Length * bx.Width;
		return hCode.GetHashCode();
	}
}
/* This example produces the following output:
 * 
      Boxes equality by dimensions:
      Added red, Count = 1, HashCode = 46104728
      Added green, Count = 2, HashCode = 12289376
      A box equal to blue is already in the collection.
      Added yellow, Count = 3, HashCode = 43495525

      Boxes equality by volume:
      Added pink, Count = 1, HashCode = 55915408
      Added orange, Count = 2, HashCode = 33476626
      A box equal to purple is already in the collection.
      A box equal to brown is already in the collection.
 * 
*/

Universal Windows Platform
Available since 8
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show:
© 2016 Microsoft