473,394 Members | 1,879 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

ReferenceEquals

In C# these are equivalent, right?

if (ReferenceEquals(objectA, objectB))
{
}

and

if (objectA == objectB)
{
}
Nov 16 '05 #1
6 5761
> In C# these are equivalent, right?

if (ReferenceEquals(objectA, objectB))
{
}

and

if (objectA == objectB)
{
}


The method System.Object.ReferenceEquals() always compares references.
Although a class can provide its own behavior for the equality operator
(below), that re-defined operator isn't invoked if the operator is called
via a reference to System.Object. Given this class:

public class EvenOdd
{
public int val;
public static bool operator==(EvenOdd left, EvenOdd right)
{
return left.val % 2 == right.val % 2;
}
public static bool operator!=(EvenOdd left, EvenOdd right)
{
return ! (left == right);
}
}

You'll get different results, depending on whether you invoke the comparison
via a reference to EvenOdd or a reference to System.Object.

If you create two EvenOdd instances:

EvenOdd a = new EvenOdd();
EvenOdd b = new EvenOdd();
a.val = 2;
b.val = 4;

Then call this method:

static void TestObject(object thing1, object thing2)
{
Console.WriteLine("Reference equals: {0}",
object.ReferenceEquals(thing1, thing2));

Console.WriteLine("Equality operator: {0}", thing1==thing2);
}

False is displayed twice to the console.

However, for a slightly different case:

static void TestEvenOdd(EvenOdd thing1, EvenOdd thing2)
{
Console.WriteLine("Reference equals: {0}",
object.ReferenceEquals(thing1, thing2));

Console.WriteLine("Equality operator: {0}", thing1 == thing2);
}

False is printed for the first case, and True for the second.

You might want to avoid this problem by overriding the virtual Equals method
if your redefinition of equality is meant to be true even when accessed via
a base type reference:

// EvenOdd, version 2
public class EvenOdd
{
public int val;
public static bool operator==(EvenOdd left, EvenOdd right)
{
return left.val % 2 == right.val % 2;
}
public static bool operator!=(EvenOdd left, EvenOdd right)
{
return ! (left == right);
}

public override bool Equals(object obj)
{
// Error-handling removed...
return ((EvenOdd)obj).val % 2 == val % 2;
}
}

With the Equals method, the proper equality comparison can be made through
any type of reference. This method displays False, then True (as expected):
static void TestEquals(object thing1, object thing2)
{
Console.WriteLine("Reference equals: {0}",
object.ReferenceEquals(thing1, thing2));

Console.WriteLine("Equals method: {0}", thing1.Equals(thing2));
}
--
Mickey Williams
Author, "Microsoft Visual C# .NET Core Reference", MS Press
www.servergeek.com/blogs/mickey
Nov 16 '05 #2
It depends on the class. If the class is String, then no. If the class is
a user-defined class and it overloads ==, then that operator works as it is
defined. For all other classes, yes they are equivalent.

http://msdn.microsoft.com/library/de...tyoperator.asp
http://msdn.microsoft.com/library/de...rpspec_7_9.asp

Brad Williams
"Daniel Billingsley" <db**********@NO.durcon.SPAAMM.com> wrote in message
news:u0**************@TK2MSFTNGP10.phx.gbl...
In C# these are equivalent, right?

if (ReferenceEquals(objectA, objectB))
{
}

and

if (objectA == objectB)
{
}

Nov 16 '05 #3
Daniel Billingsley <db**********@NO.durcon.SPAAMM.com> wrote:
In C# these are equivalent, right?

if (ReferenceEquals(objectA, objectB))
{
}

and

if (objectA == objectB)
{
}


Only if objectA and objectB are variables declared to be type object or
some other type which doesn't override ==. For instance, with strings,

if (stringA==stringB)

is equivalent to

if (String.Equals(stringA, stringB))

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #4
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Only if objectA and objectB are variables declared to be type object or
some other type which doesn't override ==. For instance, with strings,

if (stringA==stringB)

is equivalent to

if (String.Equals(stringA, stringB))


It doesn't matter so much what the type of the object is, as much as the
type of reference to the object (or maybe that's what you meant). It gets
really tricky with edge cases for strings. If the strings are tested via a
reference to object rather than string, then Equals and == can return
different values.

Because they aren't interned, the two following string instances have two
separate references to two separate objects, and return true if compared
with the Equals method or the == operator via a string reference:
string x = new string(new char[]{'f', 'o', 'o'});
string y = new string(new char[]{'f', 'o', 'o'});

// Displays False, True, True
Console.WriteLine("Reference equals: {0}",
object.ReferenceEquals(x, y));
Console.WriteLine("Equality operator: {0}", x==y);
Console.WriteLine("Equals method: {0}", x.Equals(y));

Compare those two strings via reference to object, and you get different
results.

Of course, if you're sure that the strings are interned, then they will
share a common pooled instance:
string a = "bar";
string b = "bar";
// True
Console.WriteLine("Reference equals: {0}",
object.ReferenceEquals(a, b));

This is a degenerate case that could be somewhat mitigated by explicitly
interning the strings as they are composed. In practice though, there's no
way to be 100% sure that an alledgedly cooperating assembly is causing
strings to be interned while composing.

--
Mickey Williams
Author, "Microsoft Visual C# .NET Core Reference", MS Press
www.servergeek.com/blogs/mickey
Nov 16 '05 #5
<"Mickey Williams" <my first name at servergeek.com>> wrote:
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Only if objectA and objectB are variables declared to be type object or
some other type which doesn't override ==. For instance, with strings,

if (stringA==stringB)

is equivalent to

if (String.Equals(stringA, stringB))


It doesn't matter so much what the type of the object is, as much as the
type of reference to the object (or maybe that's what you meant).


Yes - that's why I specifically used which type the *variables* are
declared to be, rather than which type the objects are :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #6
Thanks everyone. It seems I always get carried away trying to be brief and
go too far.

I am talking specifically where objectA and objectB are declared as and
refer to a class that I've written which doesn't override == or Equals().

It was actually while looking at some sample code from another person, and I
just thought == seemed more straightforward. No, wait a minute, the
original code was in VB.NET. Given the differences between Is in the two
languages, and between = (VB) and == (C#) I guess ReferenceEquals() is a
nice consistent way of getting exactly what was desired - to see if the
variables refer to the same object.

"Daniel Billingsley" <db**********@NO.durcon.SPAAMM.com> wrote in message
news:u0**************@TK2MSFTNGP10.phx.gbl...
In C# these are equivalent, right?

if (ReferenceEquals(objectA, objectB))
{
}

and

if (objectA == objectB)
{
}

Nov 16 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Holbox | last post by:
Hi people, look at this (console project) sub main dim a as string = "Hola" dim b as string = "Hola" dim c as string = new string("Hola") dim d as string = new string("Hola")
2
by: Kevin B Ebert | last post by:
Today, I ran into something I didn't quite expect. I'm sure there is a logical explanation for it so I want to post it and see if anyone can explain the difference to me. I came across a...
3
by: Fei Li | last post by:
Hi, take string class as an example, who can explain the difference? Thanks
4
by: Kiran A K | last post by:
hi, consider the following piece of code: string s1 = "kiran"; string s3 = s1.Clone() as string; Console.WriteLine(System.Object.ReferenceEquals(s1, s3)); The above piece of code gave me...
20
by: Marcel Hug | last post by:
Hi NG! In my book I have the following code simple and I tested it: public class Base : ICloneable { public int Age; public string Name; public Base(string myname)
10
by: Bruce | last post by:
I posted this on the dotnet.languages.vc group but did not get a response. I figure that I could apply what I learn from CSharp to VC, so here goes. I have a class in a class assembly, that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.