System.Object.Equals yöntemi

Uyarı

Bu makale, bu API'nin başvuru belgelerine ek açıklamalar sağlar.

Bu makale Object.Equals(Object) yöntemiyle ilgilidir.

Geçerli örnek ile obj parametre arasındaki karşılaştırma türü, geçerli örneğin bir başvuru türü mü yoksa bir değer türü mü olduğuna bağlıdır.

  • Geçerli örnek bir referans türüyse, Equals(Object) yöntemi referans eşitliğini sınar ve Equals(Object) yöntemine yapılan çağrı, ReferenceEquals yöntemine yapılan çağrıyla eşdeğerdir. Başvuru eşitliği, karşılaştırılan nesne değişkenlerinin aynı nesneye başvurduğunu gösterir. Aşağıdaki örnekte bu tür bir karşılaştırmanın sonucu gösterilmektedir. Bir başvuru türü olan bir Person sınıfı tanımlar ve aynı değere sahip iki yeni Person nesnenin Personperson1aörneğini oluşturmak için sınıf oluşturucuyu çağırırperson2. Başka bir nesne değişkeni olan person1a'a da person1b'yi atar. Örnekteki çıktının gösterdiği gibi, person1a ve person1b, aynı nesneye başvurdukları için eşittir. Ancak, person1a ve person2 aynı değere sahip olsalar da eşit değildir.

    using System;
    
    // Define a reference type that does not override Equals.
    public class Person
    {
       private string personName;
    
       public Person(string name)
       {
          this.personName = name;
       }
    
       public override string ToString()
       {
          return this.personName;
       }
    }
    
    public class Example1
    {
       public static void Main()
       {
          Person person1a = new Person("John");
          Person person1b = person1a;
          Person person2 = new Person(person1a.ToString());
    
          Console.WriteLine("Calling Equals:");
          Console.WriteLine($"person1a and person1b: {person1a.Equals(person1b)}");
          Console.WriteLine($"person1a and person2: {person1a.Equals(person2)}");
    
          Console.WriteLine("\nCasting to an Object and calling Equals:");
          Console.WriteLine($"person1a and person1b: {((object) person1a).Equals((object) person1b)}");
          Console.WriteLine($"person1a and person2: {((object) person1a).Equals((object) person2)}");
       }
    }
    // The example displays the following output:
    //       person1a and person1b: True
    //       person1a and person2: False
    //
    //       Casting to an Object and calling Equals:
    //       person1a and person1b: True
    //       person1a and person2: False
    
    // Define a reference type that does not override Equals.
    type Person(name) =
        override _.ToString() =
            name
    
    let person1a = Person "John"
    let person1b = person1a
    let person2 = Person(string person1a)
    
    printfn "Calling Equals:"
    printfn $"person1a and person1b: {person1a.Equals person1b}"
    printfn $"person1a and person2: {person1a.Equals person2}"
    
    printfn "\nCasting to an Object and calling Equals:"
    printfn $"person1a and person1b: {(person1a :> obj).Equals(person1b :> obj)}"
    printfn $"person1a and person2: {(person1a :> obj).Equals(person2 :> obj)}"
    // The example displays the following output:
    //       person1a and person1b: True
    //       person1a and person2: False
    //
    //       Casting to an Object and calling Equals:
    //       person1a and person1b: True
    //       person1a and person2: False
    
    ' Define a reference type that does not override Equals.
    Public Class Person1
        Private personName As String
    
        Public Sub New(name As String)
            Me.personName = name
        End Sub
    
        Public Overrides Function ToString() As String
            Return Me.personName
        End Function
    End Class
    
    Module Example0
        Public Sub Main()
            Dim person1a As New Person1("John")
            Dim person1b As Person1 = person1a
            Dim person2 As New Person1(person1a.ToString())
    
            Console.WriteLine("Calling Equals:")
            Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b))
            Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2))
            Console.WriteLine()
    
            Console.WriteLine("Casting to an Object and calling Equals:")
            Console.WriteLine("person1a and person1b: {0}", CObj(person1a).Equals(CObj(person1b)))
            Console.WriteLine("person1a and person2: {0}", CObj(person1a).Equals(CObj(person2)))
        End Sub
    End Module
    ' The example displays the following output:
    '       Calling Equals:
    '       person1a and person1b: True
    '       person1a and person2: False
    '       
    '       Casting to an Object and calling Equals:
    '       person1a and person1b: True
    '       person1a and person2: False
    
  • Geçerli örnek bir değer türüyse, Equals(Object) yöntem değer eşitliğini sınar. Değer eşitliği şu anlama gelir:

    • İki nesne aynı türdedir. Aşağıdaki örnekte gösterildiği gibi, değeri 12 olan bir Byte nesne 12 değerine sahip bir Int32 nesneye eşit değildir, çünkü iki nesne farklı çalışma zamanı türlerine sahiptir.

      byte value1 = 12;
      int value2 = 12;
      
      object object1 = value1;
      object object2 = value2;
      
      Console.WriteLine($"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals(object2)}");
      
      // The example displays the following output:
      //        12 (Byte) = 12 (Int32): False
      
      let value1 = 12uy
      let value2 = 12
      
      let object1 = value1 :> obj
      let object2 = value2 :> obj
      
      printfn $"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals object2}"
      
      // The example displays the following output:
      //        12 (Byte) = 12 (Int32): False
      
      Module Example2
          Public Sub Main()
              Dim value1 As Byte = 12
              Dim value2 As Integer = 12
      
              Dim object1 As Object = value1
              Dim object2 As Object = value2
      
              Console.WriteLine("{0} ({1}) = {2} ({3}): {4}",
                              object1, object1.GetType().Name,
                              object2, object2.GetType().Name,
                              object1.Equals(object2))
          End Sub
      End Module
      ' The example displays the following output:
      '       12 (Byte) = 12 (Int32): False
      
    • İki nesnenin genel ve özel alanlarının değerleri eşittir. Aşağıdaki örnek değer eşitliğini sınar. Bir değer türü olan bir Person yapı tanımlar ve aynı değere sahip iki yeni Person nesnenin Personperson1örneğini oluşturmak için sınıf oluşturucuyu çağırırperson2. Örnekteki çıktıda gösterildiği gibi, iki nesne değişkeni farklı nesnelere başvuruda bulunmasına rağmen, özel person1 alan için aynı değere sahip oldukları için person2 ve personName eşittir.

      using System;
      
      // Define a value type that does not override Equals.
      public struct Person3
      {
         private string personName;
      
         public Person3(string name)
         {
            this.personName = name;
         }
      
         public override string ToString()
         {
            return this.personName;
         }
      }
      
      public struct Example3
      {
         public static void Main()
         {
            Person3 person1 = new Person3("John");
            Person3 person2 = new Person3("John");
      
            Console.WriteLine("Calling Equals:");
            Console.WriteLine(person1.Equals(person2));
      
            Console.WriteLine("\nCasting to an Object and calling Equals:");
            Console.WriteLine(((object) person1).Equals((object) person2));
         }
      }
      // The example displays the following output:
      //       Calling Equals:
      //       True
      //
      //       Casting to an Object and calling Equals:
      //       True
      
      // Define a value type that does not override Equals.
      [<Struct>]
      type Person(personName: string) =
          override _.ToString() =
              personName
      
      let person1 = Person "John"
      let person2 = Person "John"
      
      printfn "Calling Equals:"
      printfn $"{person1.Equals person2}"
      
      printfn $"\nCasting to an Object and calling Equals:"
      printfn $"{(person1 :> obj).Equals(person2 :> obj)}"
      // The example displays the following output:
      //       Calling Equals:
      //       True
      //
      //       Casting to an Object and calling Equals:
      //       True
      
      ' Define a value type that does not override Equals.
      Public Structure Person4
          Private personName As String
      
          Public Sub New(name As String)
              Me.personName = name
          End Sub
      
          Public Overrides Function ToString() As String
              Return Me.personName
          End Function
      End Structure
      
      Module Example4
          Public Sub Main()
              Dim p1 As New Person4("John")
              Dim p2 As New Person4("John")
      
              Console.WriteLine("Calling Equals:")
              Console.WriteLine(p1.Equals(p2))
              Console.WriteLine()
      
              Console.WriteLine("Casting to an Object and calling Equals:")
              Console.WriteLine(CObj(p1).Equals(p2))
          End Sub
      End Module
      ' The example displays the following output:
      '       Calling Equals:
      '       True
      '       
      '       Casting to an Object and calling Equals:
      '       True
      

Object sınıfı .NET'teki tüm türlerin temel sınıfı olduğundan, Object.Equals(Object) yöntemi diğer tüm türler için varsayılan eşitlik karşılaştırmasını sağlar. Ancak türler genellikle değer eşitliğini uygulamak için Equals yöntemini geçersiz kılar. Daha fazla bilgi için, Arayanlar için Notlar ve Devralanlar için Notlar bölümlerine bakın.

Windows Çalışma Zamanı notları

Windows Çalışma Zamanı'nda bir sınıfta `Equals(Object)` yöntem aşırı yüklemesini çağırdığınızda, `Equals(Object)`'i geçersiz kılmayan sınıflar için varsayılan davranışı sağlar. Bu, .NET'in Windows Çalışma Zamanı için sağladığı desteğin bir parçasıdır (bkz. Windows Mağazası Uygulamaları ve Windows Çalışma Zamanı için .NET Desteği). Windows Çalışma Zamanı'ndaki sınıflar Object devralmaz ve şu anda bir Equals(Object) yöntemini uygulamaz. Ancak, C# veya Visual Basic kodunuzda kullandığınızda ToString, Equals(Object) ve GetHashCode yöntemlerine sahipmiş gibi görünürler ve .NET bu yöntemler için varsayılan davranışı sağlar.

Uyarı

C# veya Visual Basic ile yazılan Windows Çalışma Zamanı sınıfları, Equals(Object) metot aşırı yüklemelerini geçersiz kılabilir.

Arayanlar için notlar

Türetilmiş sınıflar genellikle değer eşitliğini uygulamak için Object.Equals(Object) yöntemini geçersiz kılar. Ayrıca, türler genellikle arabirimini uygulayarak Equals yöntemine IEquatable<T> sık sık ek olarak kesin olarak belirlenmiş bir aşırı yükleme sağlar. Eşitlik test etmek için Equals yöntemini çağırdığınızda, geçerli örneğin Object.Equals öğesini geçersiz kılıp kılmadığını bilmeniz ve belirli bir Equals yöntem çağrısının çözülme biçimini anlamanız gerekir. Aksi takdirde, hedeflediğinizden farklı bir eşitlik testi gerçekleştiriyor olabilirsiniz ve yöntem beklenmeyen bir değer döndürebilir.

Aşağıdaki örnek, bir gösterim sağlar. Aynı dizelere sahip üç StringBuilder nesnenin örneğini oluşturur ve ardından yöntemlere Equals dört çağrı yapar. İlk yöntem çağrısı true döndürür ve kalan üçü false döndürür.

using System;
using System.Text;

public class Example5
{
   public static void Main()
   {
      StringBuilder sb1 = new StringBuilder("building a string...");
      StringBuilder sb2 = new StringBuilder("building a string...");

      Console.WriteLine($"sb1.Equals(sb2): {sb1.Equals(sb2)}");
      Console.WriteLine($"((Object) sb1).Equals(sb2): {((Object) sb1).Equals(sb2)}");
      Console.WriteLine($"Object.Equals(sb1, sb2): {Object.Equals(sb1, sb2)}");

      Object sb3 = new StringBuilder("building a string...");
      Console.WriteLine($"\nsb3.Equals(sb2): {sb3.Equals(sb2)}");
   }
}
// The example displays the following output:
//       sb1.Equals(sb2): True
//       ((Object) sb1).Equals(sb2): False
//       Object.Equals(sb1, sb2): False
//
//       sb3.Equals(sb2): False
open System
open System.Text

let sb1 = StringBuilder "building a string..."
let sb2 = StringBuilder "building a string..."

printfn $"sb1.Equals(sb2): {sb1.Equals sb2}"
printfn $"((Object) sb1).Equals(sb2): {(sb1 :> obj).Equals sb2}"
                  
printfn $"Object.Equals(sb1, sb2): {Object.Equals(sb1, sb2)}"

let sb3 = StringBuilder "building a string..."
printfn $"\nsb3.Equals(sb2): {sb3.Equals sb2}"
// The example displays the following output:
//       sb1.Equals(sb2): True
//       ((Object) sb1).Equals(sb2): False
//       Object.Equals(sb1, sb2): False
//
//       sb3.Equals(sb2): False
Imports System.Text

Module Example5
    Public Sub Main()
        Dim sb1 As New StringBuilder("building a string...")
        Dim sb2 As New StringBuilder("building a string...")

        Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2))
        Console.WriteLine("CObj(sb1).Equals(sb2): {0}",
                        CObj(sb1).Equals(sb2))
        Console.WriteLine("Object.Equals(sb1, sb2): {0}",
                        Object.Equals(sb1, sb2))

        Console.WriteLine()
        Dim sb3 As Object = New StringBuilder("building a string...")
        Console.WriteLine("sb3.Equals(sb2): {0}", sb3.Equals(sb2))
    End Sub
End Module
' The example displays the following output:
'       sb1.Equals(sb2): True
'       CObj(sb1).Equals(sb2): False
'       Object.Equals(sb1, sb2): False
'
'       sb3.Equals(sb2): False

İlk durumda, değer eşitliğini test eden ağır tipli StringBuilder.Equals(StringBuilder) yöntem aşırı yüklemesi çağrılır. İki StringBuilder nesneye atanan dizeler eşit olduğundan yöntemi döndürür true. Ancak, StringBuilder geçersiz kılmaz Object.Equals(Object). Bu nedenle, StringBuilder nesnesi Object türüne dönüştürüldüğünde, bir StringBuilder örneği bir Object türündeki değişkene atandığında ve Object.Equals(Object, Object) yöntemi iki StringBuilder nesnesi aldığında, varsayılan Object.Equals(Object) yöntemi çağrılır. Bir StringBuilder referans türü olduğundan, iki StringBuilder nesnesinin ReferenceEquals yöntemine geçirilmesiyle aynı anlama gelir. Her üç StringBuilder nesne de aynı dizeleri içerse de, üç ayrı nesneye başvurur. Sonuç olarak, bu üç yöntem çağrısı false döndürür.

yöntemini çağırarak başvuru eşitliği için geçerli nesneyi başka bir nesneyle ReferenceEquals karşılaştırabilirsiniz. Visual Basic'te anahtar sözcüğünü is de kullanabilirsiniz (örneğin, If Me Is otherObject Then ...).

Devralıcılar için notlar

Kendi türünüzü tanımladığınızda, bu tür, temel türünün Equals yönteminde tanımlanan işlevselliği devralır. Aşağıdaki tabloda, .NET'teki ana tür kategorileri için yönteminin varsayılan uygulaması Equals listelenmiştir.

Tür kategorisi Tarafından tanımlanan eşitlik Yorumlar
Öğeden doğrudan türetilen sınıf Object Object.Equals(Object) Başvuru eşitliği; Object.ReferenceEquals çağırmaya eşdeğerdir.
Yapı ValueType.Equals Değer eşitliği; yansıma kullanarak doğrudan bayt bayt karşılaştırması veya alan ölçütü karşılaştırması.
Numaralandırma Enum.Equals Değerler aynı numaralandırma türüne ve aynı temel değere sahip olmalıdır.
Temsilci MulticastDelegate.Equals Temsilciler aynı çağrı listeleriyle aynı türe sahip olmalıdır.
Arayüz Object.Equals(Object) Başvuru eşitliği.

Değer türleri için her zaman Equals'ü aşmalısınız, çünkü yansımaya dayanan eşitlik testleri düşük performans gösterir. Bir başvuru türünün varsayılan uygulamasını, referans eşitliği yerine değer eşitliğini test etmek ve değer eşitliğinin ne anlama geldiğini net bir şekilde tanımlamak için geçersiz kılabilirsiniz. Aynı değere sahip olduklarında, iki nesne aynı örnek olmasalar bile, Equals'nin bu tür uygulamaları true döndürür. Türün uygulayıcısı nesnenin değerinin ne olduğuna karar verir, ancak genellikle nesnenin örnek değişkenlerinde depolanan verilerin bir kısmı veya tümüdür. Örneğin, bir String nesnenin değeri dizenin karakterlerini temel alır; String.Equals(Object) yöntemi, aynı sırada aynı karakterleri içeren iki dize örneği için döndürülecek Object.Equals(Object) yöntemi geçersiz kılartrue.

Aşağıdaki örnek, değer eşitliğini test etmek için Object.Equals(Object) yönteminin nasıl geçersiz kılınacağını göstermektedir. Equals yöntemini Person sınıfı için geçersiz kılar. Temel sınıf eşitlik uygulaması kabul edilirse Person , iki Person nesne yalnızca tek bir nesneye başvuruda bulunduklarında eşit olur. Ancak, bu durumda iki Person nesne özelliği için Person.Id aynı değere sahipse eşittir.

public class Person6
{
   private string idNumber;
   private string personName;

   public Person6(string name, string id)
   {
      this.personName = name;
      this.idNumber = id;
   }

   public override bool Equals(Object obj)
   {
      Person6 personObj = obj as Person6;
      if (personObj == null)
         return false;
      else
         return idNumber.Equals(personObj.idNumber);
   }

   public override int GetHashCode()
   {
      return this.idNumber.GetHashCode();
   }
}

public class Example6
{
   public static void Main()
   {
      Person6 p1 = new Person6("John", "63412895");
      Person6 p2 = new Person6("Jack", "63412895");
      Console.WriteLine(p1.Equals(p2));
      Console.WriteLine(Object.Equals(p1, p2));
   }
}
// The example displays the following output:
//       True
//       True
open System

type Person(name, id) =
    member _.Name = name
    member _.Id = id

    override _.Equals(obj) =
        match obj with
        | :? Person as personObj ->
            id.Equals personObj.Id
        | _ -> 
            false

    override _.GetHashCode() =
        id.GetHashCode()

let p1 = Person("John", "63412895")
let p2 = Person("Jack", "63412895")
printfn $"{p1.Equals p2}"
printfn $"{Object.Equals(p1, p2)}"
// The example displays the following output:
//       True
//       True
Public Class Person
   Private idNumber As String
   Private personName As String
   
   Public Sub New(name As String, id As String)
      Me.personName = name
      Me.idNumber = id
   End Sub
   
   Public Overrides Function Equals(obj As Object) As Boolean
      Dim personObj As Person = TryCast(obj, Person) 
      If personObj Is Nothing Then
         Return False
      Else
         Return idNumber.Equals(personObj.idNumber)
      End If   
   End Function
   
   Public Overrides Function GetHashCode() As Integer
      Return Me.idNumber.GetHashCode() 
   End Function
End Class

Module Example6
    Public Sub Main()
        Dim p1 As New Person("John", "63412895")
        Dim p2 As New Person("Jack", "63412895")
        Console.WriteLine(p1.Equals(p2))
        Console.WriteLine(Object.Equals(p1, p2))
    End Sub
End Module
' The example displays the following output:
'       True
'       True

Geçersiz kılmaya Equals ek olarak, eşitlik için kesin olarak belirlenmiş bir test sağlamak amacıyla IEquatable<T> arabirimini uygulayabilirsiniz.

Aşağıdaki deyimler, yönteminin Equals(Object) tüm uygulamaları için doğru olmalıdır. listesinde, x, yve znull olmayan nesne başvurularını temsil eder.

  • x.Equals(x) döndürür true.

  • x.Equals(y) ile aynı değeri y.Equals(x)döndürür.

  • x.Equals(y), hem true hem de xy ise NaN döndürür.

  • Eğer (x.Equals(y) && y.Equals(z))true döndürürse, x.Equals(z)true döndürür.

  • x.Equals(y)'ün ardışık çağrıları, x ve y tarafından başvurulan nesneler değiştirilmediği sürece aynı değeri döndürür.

  • x.Equals(null) döndürür false.

uygulamaları Equals özel durumlar oluşturmamalıdır; her zaman bir değer döndürmelidir. Örneğin, objnull ise Equals yöntemi bir false atmak yerine ArgumentNullException döndürmelidir.

şu Equals(Object)'yi geçersiz kılarken bu yönergeleri izleyin:

  • IComparable uygulayan türler Equals(Object)'i geçersiz kılmalıdır.

  • Equals(Object)'yi geçersiz kılan türlerin GetHashCode'yi de geçersiz kılması gerekir; aksi takdirde karma tablolar düzgün çalışmayabilir.

  • Eşitlik için güçlü bir şekilde belirlenmiş testleri desteklemek amacıyla IEquatable<T> arabirimini uygulamayı düşünmelisiniz. Uygulamanız IEquatable<T>.Equals ile Equalstutarlı sonuçlar döndürmelidir.

  • Programlama diliniz operatör aşırı yüklemesini destekliyorsa ve belirli bir tür için eşitlik operatörünü aşırı yüklüyorsanız, eşitlik operatörüyle aynı sonucu döndürmek için Equals(Object) yöntemini de geçersiz kılmanız gerekir. Bu, Equals (örneğin ArrayList ve Hashtable gibi) kullanan sınıf kitaplığı kodunun, eşitlik işlecinin uygulama kodu tarafından kullanılma şekliyle tutarlı bir şekilde davranmasını sağlamaya yardımcı olur.

Referans türleri için yönergeler

Aşağıdaki yönergeler, bir başvuru türü için geçersiz kılma Equals(Object) için geçerlidir:

  • Türün semantiğinin, türün bazı değerleri temsil ettiği gerçeğine dayalı olup olmadığını geçersiz kılmayı Equals göz önünde bulundurun.

  • Çoğu referans türü, Equals'ü geçersiz kılsalar bile eşitlik işlecini aşırı yüklememelidir. Ancak, karmaşık bir sayı türü gibi değer semantiğine sahip olması amaçlanan bir başvuru türü uyguluyorsanız, eşitlik işlecini geçersiz kılmanız gerekir.

  • Mutable başvuru türlerindeki Equals öğesini geçersiz kılmamalısınız. Bunun nedeni, Equals 'u geçersiz kılmanın, önceki bölümde açıklandığı gibi, GetHashCode yöntemini de geçersiz kılmayı gerektirmesidir. Bu, değiştirilebilir başvuru türünün örneğinin karma kodunun ömrü boyunca değişebileceği ve bu da nesnenin karma tabloda kaybolmasına neden olabileceği anlamına gelir.

Değer türleri için yönergeler

Aşağıdaki yönergeler, bir değer türü için geçersiz kılma Equals(Object) için geçerlidir:

  • Değerleri başvuru türü olan bir veya daha fazla alan içeren bir değer türü tanımlıyorsanız, öğesini geçersiz kılmalısınız Equals(Object). Equals(Object) tarafından ValueType sağlanan uygulama, alanları tüm değer türleri olan değer türleri için bayt bayt karşılaştırması gerçekleştirir, ancak alanları başvuru türlerini içeren değer türlerinin alan ölçütü karşılaştırmasını yapmak için yansıma kullanır.

  • Geçersiz kılarsanız Equals ve geliştirme diliniz operatör aşırı yüklemesini destekliyorsa, eşitlik operatörünü aşırı yüklemelisiniz.

  • Arabirimi IEquatable<T> uygulamalısınız. Kesin olarak yazılmış IEquatable<T>.Equals yönteminin çağrılması, obj bağımsız değişkenin kutulanmasını önler.

Örnekler

Aşağıdaki örnekte, değer eşitliği sağlamak üzere üzerine Point yöntemini geçersiz kılan bir Equals sınıfı ve Point3D'den türetilen bir Point sınıfı gösterilmektedir. Değer eşitliğini test etmek için Point, Object.Equals(Object)'i geçersiz kıldığından, Object.Equals(Object) yöntemi çağrılmaz. Ancak, Point3D.Equals, değer eşitliği sağlayan bir şekilde Point.Equals uyguladığı için Point, Object.Equals(Object) çağrısı yapar.

using System;

class Point2
{
    protected int x, y;

    public Point2() : this(0, 0)
    { }

    public Point2(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override bool Equals(Object obj)
    {
        //Check for null and compare run-time types.
        if ((obj == null) || !this.GetType().Equals(obj.GetType()))
        {
            return false;
        }
        else
        {
            Point2 p = (Point2)obj;
            return (x == p.x) && (y == p.y);
        }
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(x, y);
    }

    public override string ToString()
    {
        return String.Format("Point2({0}, {1})", x, y);
    }
}

sealed class Point3D : Point2
{
    int z;

    public Point3D(int x, int y, int z) : base(x, y)
    {
        this.z = z;
    }

    public override bool Equals(Object obj)
    {
        Point3D pt3 = obj as Point3D;
        if (pt3 == null)
            return false;
        else
            return base.Equals((Point2)obj) && z == pt3.z;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(base.GetHashCode(), z);
    }

    public override String ToString()
    {
        return String.Format("Point2({0}, {1}, {2})", x, y, z);
    }
}

class Example7
{
    public static void Main()
    {
        Point2 point2D = new Point2(5, 5);
        Point3D point3Da = new Point3D(5, 5, 2);
        Point3D point3Db = new Point3D(5, 5, 2);
        Point3D point3Dc = new Point3D(5, 5, -1);

        Console.WriteLine($"{point2D} = {point3Da}: {point2D.Equals(point3Da)}");
        Console.WriteLine($"{point2D} = {point3Db}: {point2D.Equals(point3Db)}");
        Console.WriteLine($"{point3Da} = {point3Db}: {point3Da.Equals(point3Db)}");
        Console.WriteLine($"{point3Da} = {point3Dc}: {point3Da.Equals(point3Dc)}");
    }
}
// The example displays the following output:
//       Point2(5, 5) = Point2(5, 5, 2): False
//       Point2(5, 5) = Point2(5, 5, 2): False
//       Point2(5, 5, 2) = Point2(5, 5, 2): True
//       Point2(5, 5, 2) = Point2(5, 5, -1): False
type Point(x, y) =
    new () = Point(0, 0)
    member _.X = x
    member _.Y = y

    override _.Equals(obj) =
        //Check for null and compare run-time types.
        match obj with
        | :? Point as p ->
            x = p.X && y = p.Y
        | _ -> 
            false

    override _.GetHashCode() =
        System.HashCode.Combine(x, y)

    override _.ToString() =
        $"Point({x}, {y})"

type Point3D(x, y, z) =
    inherit Point(x, y)
    member _.Z = z

    override _.Equals(obj) =
        match obj with
        | :? Point3D as pt3 ->
            base.Equals(pt3 :> Point) && z = pt3.Z
        | _ -> 
            false

    override _.GetHashCode() =
        System.HashCode.Combine(base.GetHashCode(), z)

    override _.ToString() =
        $"Point({x}, {y}, {z})"

let point2D = Point(5, 5)
let point3Da = Point3D(5, 5, 2)
let point3Db = Point3D(5, 5, 2)
let point3Dc = Point3D(5, 5, -1)

printfn $"{point2D} = {point3Da}: {point2D.Equals point3Da}"
printfn $"{point2D} = {point3Db}: {point2D.Equals point3Db}"
printfn $"{point3Da} = {point3Db}: {point3Da.Equals point3Db}"
printfn $"{point3Da} = {point3Dc}: {point3Da.Equals point3Dc}"
// The example displays the following output:
//       Point(5, 5) = Point(5, 5, 2): False
//       Point(5, 5) = Point(5, 5, 2): False
//       Point(5, 5, 2) = Point(5, 5, 2): True
//       Point(5, 5, 2) = Point(5, 5, -1): False
Class Point1
    Protected x, y As Integer

    Public Sub New()
        Me.x = 0
        Me.y = 0
    End Sub

    Public Sub New(x As Integer, y As Integer)
        Me.x = x
        Me.y = y
    End Sub

    Public Overrides Function Equals(obj As Object) As Boolean
        ' Check for null and compare run-time types.
        If obj Is Nothing OrElse Not Me.GetType().Equals(obj.GetType()) Then
            Return False
        Else
            Dim p As Point1 = DirectCast(obj, Point1)
            Return x = p.x AndAlso y = p.y
        End If
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return HashCode.Combine(x, y)
    End Function

    Public Overrides Function ToString() As String
        Return String.Format("Point1({0}, {1})", x, y)
    End Function
End Class

Class Point3D : Inherits Point1
    Private z As Integer

    Public Sub New(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer)
        MyBase.New(x, y)
        Me.z = z
    End Sub

    Public Overrides Function Equals(ByVal obj As Object) As Boolean
        Dim pt3 As Point3D = TryCast(obj, Point3D)
        If pt3 Is Nothing Then
            Return False
        Else
            Return MyBase.Equals(CType(pt3, Point1)) AndAlso z = pt3.z
        End If
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return HashCode.Combine(MyBase.GetHashCode(), z)
    End Function

    Public Overrides Function ToString() As String
        Return String.Format("Point1({0}, {1}, {2})", x, y, z)
    End Function
End Class

Module Example1
    Public Sub Main()
        Dim point2D As New Point1(5, 5)
        Dim point3Da As New Point3D(5, 5, 2)
        Dim point3Db As New Point3D(5, 5, 2)
        Dim point3Dc As New Point3D(5, 5, -1)

        Console.WriteLine("{0} = {1}: {2}",
                          point2D, point3Da, point2D.Equals(point3Da))
        Console.WriteLine("{0} = {1}: {2}",
                          point2D, point3Db, point2D.Equals(point3Db))
        Console.WriteLine("{0} = {1}: {2}",
                          point3Da, point3Db, point3Da.Equals(point3Db))
        Console.WriteLine("{0} = {1}: {2}",
                          point3Da, point3Dc, point3Da.Equals(point3Dc))
    End Sub
End Module
' The example displays the following output
'       Point1(5, 5) = Point1(5, 5, 2): False
'       Point1(5, 5) = Point1(5, 5, 2): False
'       Point1(5, 5, 2) = Point1(5, 5, 2): True
'       Point1(5, 5, 2) = Point1(5, 5, -1): False

Point.Equals yöntemi, obj argümanın null olmadığından ve bu nesneyle aynı türde bir örneğe başvurduğundan emin olmak için denetler. Denetimlerden biri başarısız olursa yöntemi döndürür false.

Point.Equals yöntemi, iki nesnenin çalışma zamanı türlerinin aynı olup olmadığını belirlemek için GetType yöntemini çağırır. Yöntem, C#'ta obj is Point biçiminde veya Visual Basic'te TryCast(obj, Point) biçiminde bir denetim kullandıysa, true bir obj türetilmiş sınıf örneği olduğunda bile, denetim Point döndürür, ancak obj ve geçerli örnek aynı çalışma zamanı türünde değildir. Her iki nesnenin de aynı türde olduğunu doğruladıktan sonra, yöntem obj türünü Point türüne dönüştürür ve iki nesnenin örnek alanlarını karşılaştırmanın sonucunu döndürür.

Point3D.Equals içinde, Point.Equals öğesini geçersiz kılan devralınan Object.Equals(Object) yöntemi, başka bir işlem yapılmadan önce çağrılır. Kapalı bir sınıf olduğu için (Point3D Visual Basic'te), C#'ta NotInheritable veya Visual Basic'te obj is Point biçiminde yapılan bir kontrol, TryCast(obj, Point)'nin bir obj nesnesi olduğundan emin olunması için yeterlidir. Eğer Point3D bir nesne ise, bir Point nesneye dönüştürülür ve Equals'nin temel sınıf uygulamasına aktarılır. Sadece devralınan Point.Equals yöntem true döndürdüğünde, yöntem türetilmiş sınıftaki z örnek alanlarını karşılaştırır.

Aşağıdaki örnek, bir Rectangle dikdörtgeni dahili olarak iki Point nesne olarak uygulayan bir sınıfı tanımlar. Rectangle sınıfı, değer eşitliğini sağlamak için Object.Equals(Object)'i de geçersiz kılar.

using System;

class Rectangle
{
   private Point a, b;

   public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY)
   {
      this.a = new Point(upLeftX, upLeftY);
      this.b = new Point(downRightX, downRightY);
   }

   public override bool Equals(Object obj)
   {
      // Perform an equality check on two rectangles (Point object pairs).
      if (obj == null || GetType() != obj.GetType())
          return false;
      Rectangle r = (Rectangle)obj;
      return a.Equals(r.a) && b.Equals(r.b);
   }

   public override int GetHashCode()
   {
      return Tuple.Create(a, b).GetHashCode();
   }

    public override String ToString()
    {
       return String.Format("Rectangle({0}, {1}, {2}, {3})",
                            a.x, a.y, b.x, b.y);
    }
}

class Point
{
  internal int x;
  internal int y;

  public Point(int X, int Y)
  {
     this.x = X;
     this.y = Y;
  }

  public override bool Equals (Object obj)
  {
     // Performs an equality check on two points (integer pairs).
     if (obj == null || GetType() != obj.GetType()) return false;
     Point p = (Point)obj;
     return (x == p.x) && (y == p.y);
  }

  public override int GetHashCode()
  {
     return Tuple.Create(x, y).GetHashCode();
  }
}

class Example
{
   public static void Main()
   {
      Rectangle r1 = new Rectangle(0, 0, 100, 200);
      Rectangle r2 = new Rectangle(0, 0, 100, 200);
      Rectangle r3 = new Rectangle(0, 0, 150, 200);

      Console.WriteLine($"{r1} = {r2}: {r1.Equals(r2)}");
      Console.WriteLine($"{r1} = {r3}: {r1.Equals(r3)}");
      Console.WriteLine($"{r2} = {r3}: {r2.Equals(r3)}");
   }
}
// The example displays the following output:
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
type Point(x, y) =
    member _.X = x
    member _.Y = y

    override _.Equals(obj) =
        // Performs an equality check on two points (integer pairs).
        match obj with
        | :? Point as p ->
            x = p.X && y = p.Y
        | _ ->
            false
    
    override _.GetHashCode() =
        (x, y).GetHashCode()

type Rectangle(upLeftX, upLeftY, downRightX, downRightY) =
    let a = Point(upLeftX, upLeftY)
    let b = Point(downRightX, downRightY)
    
    member _.UpLeft = a
    member _.DownRight = b

    override _.Equals(obj) =
        // Perform an equality check on two rectangles (Point object pairs).
        match obj with
        | :? Rectangle as r ->
            a.Equals(r.UpLeft) && b.Equals(r.DownRight)
        | _ -> 
            false
        
    override _.GetHashCode() =
        (a, b).GetHashCode()

    override _.ToString() =
       $"Rectangle({a.X}, {a.Y}, {b.X}, {b.Y})"

let r1 = Rectangle(0, 0, 100, 200)
let r2 = Rectangle(0, 0, 100, 200)
let r3 = Rectangle(0, 0, 150, 200)

printfn $"{r1} = {r2}: {r1.Equals r2}"
printfn $"{r1} = {r3}: {r1.Equals r3}"
printfn $"{r2} = {r3}: {r2.Equals r3}"
// The example displays the following output:
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
Class Rectangle 
    Private a, b As Point
    
    Public Sub New(ByVal upLeftX As Integer, ByVal upLeftY As Integer, _
                   ByVal downRightX As Integer, ByVal downRightY As Integer) 
        Me.a = New Point(upLeftX, upLeftY)
        Me.b = New Point(downRightX, downRightY)
    End Sub 
    
    Public Overrides Function Equals(ByVal obj As [Object]) As Boolean 
        ' Performs an equality check on two rectangles (Point object pairs).
        If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
            Return False
        End If
        Dim r As Rectangle = CType(obj, Rectangle)
        Return a.Equals(r.a) AndAlso b.Equals(r.b)
    End Function

    Public Overrides Function GetHashCode() As Integer 
        Return Tuple.Create(a, b).GetHashCode()
    End Function 

    Public Overrides Function ToString() As String
       Return String.Format("Rectangle({0}, {1}, {2}, {3})",
                            a.x, a.y, b.x, b.y) 
    End Function
End Class 

Class Point
    Friend x As Integer
    Friend y As Integer
    
    Public Sub New(ByVal X As Integer, ByVal Y As Integer) 
        Me.x = X
        Me.y = Y
    End Sub 

    Public Overrides Function Equals(ByVal obj As [Object]) As Boolean 
        ' Performs an equality check on two points (integer pairs).
        If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
            Return False
        Else
           Dim p As Point = CType(obj, Point)
           Return x = p.x AndAlso y = p.y
        End If
    End Function 
    
    Public Overrides Function GetHashCode() As Integer 
        Return Tuple.Create(x, y).GetHashCode()
    End Function 
End Class  

Class Example
    Public Shared Sub Main() 
        Dim r1 As New Rectangle(0, 0, 100, 200)
        Dim r2 As New Rectangle(0, 0, 100, 200)
        Dim r3 As New Rectangle(0, 0, 150, 200)
        
        Console.WriteLine("{0} = {1}: {2}", r1, r2, r1.Equals(r2))
        Console.WriteLine("{0} = {1}: {2}", r1, r3, r1.Equals(r3))
        Console.WriteLine("{0} = {1}: {2}", r2, r3, r2.Equals(r3))
    End Sub 
End Class 
' The example displays the following output:
'    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
'    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
'    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False

C# ve Visual Basic gibi bazı diller işleci aşırı yüklemeyi destekler. Bir tür eşitlik operatörünü aşırı yüklediğinde, aynı işlevselliği sağlamak için Equals(Object) metodunu da geçersiz kılmalıdır. Bu genellikle Equals(Object) yöntemi, aşırı yüklenmiş eşitlik işleci açısından yazılarak gerçekleştirilir, aşağıdaki örnekte olduğu gibi.

using System;

public struct Complex
{
   public double re, im;

   public override bool Equals(Object obj)
   {
      return obj is Complex && this == (Complex)obj;
   }

   public override int GetHashCode()
   {
      return Tuple.Create(re, im).GetHashCode();
   }

   public static bool operator ==(Complex x, Complex y)
   {
      return x.re == y.re && x.im == y.im;
   }

   public static bool operator !=(Complex x, Complex y)
   {
      return !(x == y);
   }

    public override String ToString()
    {
       return String.Format("({0}, {1})", re, im);
    }
}

class MyClass
{
  public static void Main()
  {
    Complex cmplx1, cmplx2;

    cmplx1.re = 4.0;
    cmplx1.im = 1.0;

    cmplx2.re = 2.0;
    cmplx2.im = 1.0;

    Console.WriteLine($"{cmplx1} <> {cmplx2}: {cmplx1 != cmplx2}");
    Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}");

    cmplx2.re = 4.0;

    Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1 == cmplx2}");
    Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}");
  }
}
// The example displays the following output:
//       (4, 1) <> (2, 1): True
//       (4, 1) = (2, 1): False
//       (4, 1) = (4, 1): True
//       (4, 1) = (4, 1): True
[<Struct; CustomEquality; NoComparison>]
type Complex =
    val mutable re: double
    val mutable im: double

    override this.Equals(obj) =
        match obj with 
        | :? Complex as c when c = this -> true
        | _ -> false 

    override this.GetHashCode() =
        (this.re, this.im).GetHashCode()

    override this.ToString() =
        $"({this.re}, {this.im})"

    static member op_Equality (x: Complex, y: Complex) =
        x.re = y.re && x.im = y.im

    static member op_Inequality (x: Complex, y: Complex) =
        x = y |> not

let mutable cmplx1 = Complex()
let mutable cmplx2 = Complex()

cmplx1.re <- 4.0
cmplx1.im <- 1.0

cmplx2.re <- 2.0
cmplx2.im <- 1.0

printfn $"{cmplx1} <> {cmplx2}: {cmplx1 <> cmplx2}"
printfn $"{cmplx1} = {cmplx2}: {cmplx1.Equals cmplx2}"

cmplx2.re <- 4.0

printfn $"{cmplx1} = {cmplx2}: {cmplx1 = cmplx2}"
printfn $"{cmplx1} = {cmplx2}: {cmplx1.Equals cmplx2}"

// The example displays the following output:
//       (4, 1) <> (2, 1): True
//       (4, 1) = (2, 1): False
//       (4, 1) = (4, 1): True
//       (4, 1) = (4, 1): True
Public Structure Complex
    Public re, im As Double
    
    Public Overrides Function Equals(ByVal obj As [Object]) As Boolean 
        Return TypeOf obj Is Complex AndAlso Me = CType(obj, Complex)
    End Function 
    
    Public Overrides Function GetHashCode() As Integer 
        Return Tuple.Create(re, im).GetHashCode()
    End Function 
    
    Public Shared Operator = (x As Complex, y As Complex) As Boolean
       Return x.re = y.re AndAlso x.im = y.im
    End Operator 
    
    Public Shared Operator <> (x As Complex, y As Complex) As Boolean
       Return Not (x = y)
    End Operator 
    
    Public Overrides Function ToString() As String
       Return String.Format("({0}, {1})", re, im)
    End Function 
End Structure

Class Example8
    Public Shared Sub Main()
        Dim cmplx1, cmplx2 As Complex

        cmplx1.re = 4.0
        cmplx1.im = 1.0

        cmplx2.re = 2.0
        cmplx2.im = 1.0

        Console.WriteLine("{0} <> {1}: {2}", cmplx1, cmplx2, cmplx1 <> cmplx2)
        Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2))

        cmplx2.re = 4.0

        Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1 = cmplx2)
        Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2))
    End Sub
End Class
' The example displays the following output:
'       (4, 1) <> (2, 1): True
'       (4, 1) = (2, 1): False
'       (4, 1) = (4, 1): True
'       (4, 1) = (4, 1): True

Complex bir değer türü olduğu için türetilemez. Bu nedenle, Equals(Object) yöntemini geçersiz kılarken, her nesnenin kesin çalışma zamanı türünü belirlemek için GetType çağrısına gerek yoktur. Bunun yerine, C# dilinde is işleci veya Visual Basic'te TypeOf işleci kullanılarak obj parametresinin türü kontrol edilebilir.