Object.ReferenceEquals. The C# object.ReferenceEquals method compares references. When you allocate an object, you receive a reference containing a value indicating its memory location.
More details. The object.ReferenceEquals method gives you the ability to determine if 2 objects are in the same memory location. The data pointed to is not compared.
Example. Two StringBuilders are allocated upon the managed heap. The identifiers builder1 and builder2 are reference variables. They contain values that points to those locations on the heap.
using System;
using System.Text;
class Program
{
static void Main()
{
// Test object.ReferenceEquals.
StringBuilder builder1 = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
Console.WriteLine(object.ReferenceEquals(builder1, builder2));
builder1 = builder2;
Console.WriteLine(object.ReferenceEquals(builder1, builder2));
// Test object.ReferenceEquals on string literals.
string literal1 = "a";
string literal2 = "a";
Console.WriteLine(object.ReferenceEquals(literal1, literal2));
literal1 = literal2;
Console.WriteLine(object.ReferenceEquals(literal1, literal2));
}
}False
True
True
True
Performance. Is object.ReferenceEquals a slow or fast method call? I developed this console program that tests the performance of object.ReferenceEquals on a custom class.
Info ReferenceEquals was fast. It was a faster way of testing two objects for equality than comparing a unique Id field.
Thus With objects similar to A, object.ReferenceEquals is not slow. We can use it without too much concern.
using System;
using System.Diagnostics;
class A
{
public int Id;
}
class Program
{
const int _max = 1000000000;
static void Main()
{
bool same = true;
A a1 = new A() { Id = 1 };
A a2 = same ?
a1 :
new A() { Id = 2 };
int x = 0;
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (object.ReferenceEquals(a1, a2))
{
x++;
}
}
s1.Stop();
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
if (a1.Id == a2.Id)
{
x++;
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns"));
}
}0.32 ns [object.ReferenceEquals]
0.64 ns0.64 ns [object.ReferenceEquals]
0.64 ns
References in the C# language refer to a location in memory. By comparing references with ReferenceEquals, we determine if 2 variables have an identical location in memory.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 25, 2022 (edit).