In a .NET program that's written to follow declarative style, what are some legitimate uses for ReferenceEquals()?
ReferenceEquals() Method is used to determine whether the specified Object instances are the same instance or not. This method cannot be overridden.
To check for reference equality, use ReferenceEquals. To check for value equality, use Equals or Equals.
The Equality Operator ( ==) is the comparison operator and the Equals() method in C# is used to compare the content of a string. The Equals() method compares only content.
Not sure what you mean by "written to follow declarative style", but ReferenceEquals
is usually used when overriding the ==
operator. From http://msdn.microsoft.com/en-us/library/ms173147.aspx:
public static bool operator ==(ThreeDPoint a, ThreeDPoint b)
{
// If both are null, or both are same instance, return true.
if (System.Object.ReferenceEquals(a, b))
{
return true;
}
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null))
{
return false;
}
// Return true if the fields match:
return a.x == b.x && a.y == b.y && a.z == b.z;
}
It is important to see the Note below for the justification:
Note: A common error in overloads of operator == is to use (a == b), (a == null), or (b == null) to check for reference equality. This instead creates a call to the overloaded operator ==, causing an infinite loop. Use ReferenceEquals or cast the type to Object, to avoid the loop.
In a .NET program that's written to follow declarative style, what are some legitimate uses for ReferenceEquals()?
There is only one legitimate use of ReferenceEquals regardless of the "style" in which the program is written: to compare two references for reference equality.
If you are using ReferenceEquals for something other than comparing two references for reference equality, you're probably doing something wrong.
Well, if the design and/or usage of the related objects is such that there is never more than one instance of any object that is "equal" to any other, then it will be correct, and it's likely to be quicker than comparing some number of instance variables.
Or, as posted in another answer, you can check it first as an "easy out" and only perform a deep equals check if they are different. This usage it just a performance improvement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With