Export (0) Print
Expand All

EqualityComparer(Of T) Class

Provides a base class for implementations of the IEqualityComparer(Of T) generic interface.

System.Object
  System.Collections.Generic.EqualityComparer(Of T)

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

'Declaration
<SerializableAttribute> _
Public MustInherit Class EqualityComparer(Of T) _
	Implements IEqualityComparer, IEqualityComparer(Of T)

Type Parameters

T

The type of objects to compare.

The EqualityComparer(Of T) type exposes the following members.

  NameDescription
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEqualityComparer(Of T)Initializes a new instance of the EqualityComparer(Of T) class.
Top

  NameDescription
Public propertyStatic memberSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsDefaultReturns a default equality comparer for the type specified by the generic argument.
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(T, T)When overridden in a derived class, determines whether two objects of type T are equal.
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCode(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.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIEqualityComparer.EqualsDetermines whether the specified objects are equal.
Explicit interface implemetationPrivate methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsIEqualityComparer.GetHashCodeReturns a hash code for the specified object.
Top

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

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

We recommend that you derive from the EqualityComparer(Of T) class instead of implementing the IEqualityComparer(Of T) interface, because the EqualityComparer(Of T) class tests for equality using the IEquatable(Of T).Equals method instead of the Object.Equals method. This is consistent with the Contains, IndexOf, LastIndexOf, and Remove methods of the Dictionary(Of 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.

Imports System
Imports System.Collections
Imports System.Collections.Generic

Class Program
    Shared boxes As Dictionary(Of Box, [String])

    Public Shared Sub Main(ByVal args As String())

        Dim boxDim As New BoxSameDimensions()
        boxes = New Dictionary(Of Box, String)(boxDim)

        Console.WriteLine("Boxes equality by dimensions:")
        Dim redBox As New Box(8, 4, 8)
        Dim greenBox As New Box(8, 6, 8)
        Dim blueBox As New Box(8, 4, 8)
        Dim yellowBox As 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:")

        Dim boxVolume As New BoxSameVolume()
        boxes = New Dictionary(Of Box, String)(boxVolume)
        Dim pinkBox As New Box(8, 4, 8)
        Dim orangeBox As New Box(8, 6, 8)
        Dim purpleBox As New Box(4, 8, 8)
        Dim brownBox As New Box(8, 8, 4)
        AddBox(pinkBox, "pink")
        AddBox(orangeBox, "orange")
        AddBox(purpleBox, "purple")
        AddBox(brownBox, "brown")
    End Sub 

    Public Shared Sub AddBox(ByVal bx As Box, ByVal name As String)
        Try
            boxes.Add(bx, name)
            Console.WriteLine("Added {0}, Count = {1}, HashCode = {2}", _
                              name, boxes.Count.ToString(), bx.GetHashCode())
        Catch generatedExceptionName As ArgumentException
            Console.WriteLine("A box equal to {0} is already in the collection.", name)
        End Try 
    End Sub 
End Class 
Public Class Box
    Public Sub New(ByVal h As Integer, ByVal l As Integer, ByVal w As Integer)
        Me.Height = h
        Me.Length = l
        Me.Width = w
    End Sub 
    Private _Height As Integer 
    Public Property Height() As Integer 
        Get 
            Return _Height
        End Get 
        Set(ByVal value As Integer)
            _Height = value
        End Set 
    End Property 
    Private _Length As Integer 
    Public Property Length() As Integer 
        Get 
            Return _Length
        End Get 
        Set(ByVal value As Integer)
            _Length = value
        End Set 
    End Property 
    Private _Width As Integer 
    Public Property Width() As Integer 
        Get 
            Return _Width
        End Get 
        Set(ByVal value As Integer)
            _Width = value
        End Set 
    End Property 
End Class 


Class BoxSameDimensions
    Inherits EqualityComparer(Of Box)

    Public Overloads Overrides Function Equals(ByVal b1 As Box, _
                                      ByVal b2 As Box) As Boolean 
        If b1.Height = b2.Height And b1.Length = b2.Length _
                                    And b1.Width = b2.Width Then 
            Return True 
        Else 
            Return False 
        End If 
    End Function 


    Public Overloads Overrides Function GetHashCode(ByVal bx As Box) As Integer 
        Dim hCode As Integer = bx.Height Xor bx.Length Xor bx.Width
        Return hCode.GetHashCode()
    End Function 

End Class 

Class BoxSameVolume
    Inherits EqualityComparer(Of Box)

    Public Overloads Overrides Function Equals(ByVal b1 As Box, _
                                          ByVal b2 As Box) As Boolean 
        If b1.Height * b1.Width * b1.Length = _
                                b2.Height * b2.Width * b2.Length Then 
            Return True 
        Else 
            Return False 
        End If 
    End Function 


    Public Overloads Overrides Function GetHashCode(ByVal bx As Box) As Integer 
        Dim hCode As Integer = bx.Height Xor bx.Length Xor bx.Width
        Return hCode.GetHashCode()
    End Function 

End Class 
' 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 = 55530882 

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

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone Silverlight 8.1, Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

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