Object.ReferenceEquals(Object, Object) Método

Definición

Determina si las instancias de Object especificadas son la misma instancia.Determines whether the specified Object instances are the same instance.

public:
 static bool ReferenceEquals(System::Object ^ objA, System::Object ^ objB);
public static bool ReferenceEquals (object objA, object objB);
static member ReferenceEquals : obj * obj -> bool
Public Shared Function ReferenceEquals (objA As Object, objB As Object) As Boolean

Parámetros

objA
Object

El primer objeto que se va a comparar.The first object to compare.

objB
Object

Segundo objeto que se va a comparar.The second object to compare.

Devoluciones

Es true si objA es la misma instancia que objB, o si ambos son null; en caso contrario, es false.true if objA is the same instance as objB or if both are null; otherwise, false.

Ejemplos

En el ejemplo siguiente se usa ReferenceEquals para determinar si dos objetos son la misma instancia.The following example uses ReferenceEquals to determine if two objects are the same instance.

using namespace System;
int main()
{
   Object^ o = nullptr;
   Object^ p = nullptr;
   Object^ q = gcnew Object;
   Console::WriteLine( Object::ReferenceEquals( o, p ) );
   p = q;
   Console::WriteLine( Object::ReferenceEquals( p, q ) );
   Console::WriteLine( Object::ReferenceEquals( o, p ) );
}

/*

This code produces the following output.

True
True
False

*/
object o = null;
object p = null;
object q = new Object();

Console.WriteLine(Object.ReferenceEquals(o, p));
p = q;
Console.WriteLine(Object.ReferenceEquals(p, q));
Console.WriteLine(Object.ReferenceEquals(o, p));

// This code produces the following output:
//   True
//   True
//   False
Public Class App
    Public Shared Sub Main() 
        Dim o As Object = Nothing
        Dim p As Object = Nothing
        Dim q As New Object
        Console.WriteLine(Object.ReferenceEquals(o, p))
        p = q
        Console.WriteLine(Object.ReferenceEquals(p, q))
        Console.WriteLine(Object.ReferenceEquals(o, p))
    End Sub 
End Class 
' This code produces the following output:
'
' True
' True
' False
'

Comentarios

A diferencia del método Equals y el operador de igualdad, no se puede invalidar el método ReferenceEquals.Unlike the Equals method and the equality operator, the ReferenceEquals method cannot be overridden. Por este motivo, si desea probar la igualdad de dos referencias a objetos y no está seguro de la implementación del método Equals, puede llamar al método ReferenceEquals.Because of this, if you want to test two object references for equality and you are unsure about the implementation of the Equals method, you can call the ReferenceEquals method.

Sin embargo, el valor devuelto del método ReferenceEquals puede parecer anómalo en estos dos escenarios:However, the return value of the ReferenceEquals method may appear to be anomalous in these two scenarios:

  • Al comparar tipos de valor.When comparing value types. Si objA y objB son tipos de valor, se les aplica la conversión boxing antes de que se pasen al método ReferenceEquals.If objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method. Esto significa que si tanto objA como objB representan la misma instancia de un tipo de valor, el método ReferenceEquals devuelve false, como se muestra en el ejemplo siguiente.This means that if both objA and objB represent the same instance of a value type, the ReferenceEquals method nevertheless returns false, as the following example shows.

    int int1 = 3;
    Console.WriteLine(Object.ReferenceEquals(int1, int1));
    Console.WriteLine(int1.GetType().IsValueType);
    
    // The example displays the following output:
    //       False
    //       True
    
    Public Module Example
       Public Sub Main
          Dim int1 As Integer = 3
          Console.WriteLine(Object.ReferenceEquals(int1, int1))
          Console.WriteLine(int1.GetType().IsValueType)
       End Sub
    End Module
    ' The example displays the following output:
    '       False
    '       True
    

    Para obtener información sobre los tipos de valor de conversión boxing, consulte Boxing y unboxing.For information on boxing value types, see Boxing and Unboxing.

  • Al comparar cadenas.When comparing strings. Si objA y objB son cadenas, el método ReferenceEquals devuelve true si se trata de una cadena.If objA and objB are strings, the ReferenceEquals method returns true if the string is interned. No realiza una prueba de igualdad de valores.It does not perform a test for value equality. En el ejemplo siguiente, s1 y s2 son iguales porque son dos instancias de una sola cadena internd.In the following example, s1 and s2 are equal because they are two instances of a single interned string. Sin embargo, s3 y s4 no son iguales, porque aunque tienen valores de cadena idénticos, no se utiliza el método Intern en esa cadena.However, s3 and s4 are not equal, because although they are have identical string values, that string is not interned.

    String s1 = "String1";
    String s2 = "String1";
    Console.WriteLine("s1 = s2: {0}", Object.ReferenceEquals(s1, s2));
    Console.WriteLine("{0} interned: {1}", s1, 
                      String.IsNullOrEmpty(String.IsInterned(s1)) ? "No" : "Yes");
    
    String suffix = "A";
    String s3 = "String" + suffix;
    String s4 = "String" + suffix;
    Console.WriteLine("s3 = s4: {0}", Object.ReferenceEquals(s3, s4));
    Console.WriteLine("{0} interned: {1}", s3, 
                      String.IsNullOrEmpty(String.IsInterned(s3)) ? "No" : "Yes");
    
    // The example displays the following output:
    //       s1 = s2: True
    //       String1 interned: Yes
    //       s3 = s4: False
    //       StringA interned: No
    
    Module Example
       Public Sub Main()
          Dim s1 As String = "String1"
          Dim s2 As String = "String1"
          Console.WriteLine("s1 = s2: {0}", Object.ReferenceEquals(s1, s2))
          Console.WriteLine("{0} interned: {1}", s1, 
                            If(String.IsNullOrEmpty(String.IsInterned(s1)), "No", "Yes"))
    
          Dim suffix As String = "A"
          Dim s3 = "String" + suffix
          Dim s4 = "String" + suffix
          Console.WriteLine("s3 = s4: {0}", Object.ReferenceEquals(s3, s4))
          Console.WriteLine("{0} interned: {1}", s3, 
                            If(String.IsNullOrEmpty(String.IsInterned(s3)), "No", "Yes"))
       End Sub
    End Module
    ' The example displays the following output:
    '       s1 = s2: True
    '       String1 interned: Yes
    '       s3 = s4: False
    '       StringA interned: No
    

    Para obtener más información sobre el interning de cadenas, vea String.IsInterned.For more information about string interning, see String.IsInterned.

Se aplica a

Consulte también: