Some methods in .NET are like landmines: they lie in plain sight, they look harmless, and the compiler lets you step right on them.
Two of them are object.ReferenceEquals(object, object) and object.Equals(object). Both accept arguments of type object, which means that they accept any arguments at all, even arguments for which the answer can only ever be false. The compiler does not issue an error about such invocations, not even a warning, which is something that I, personally, find preposterous.
This post shows how you can get the compiler, or at least Visual Studio, to point out such mistakes.
object.ReferenceEquals(object, object)
The static method object.ReferenceEquals(object, object) tells you whether two references point to the same object. Since it accepts any two objects, it will compile just fine even if you give it objects of unrelated classes, which is clearly a mistake on your part, because they could not possibly be the same object. It will also compile just fine if one or more of the parameters accidentally happens to be a struct; the struct gets boxed into a new object of its own, so the result can be nothing but false.
A type-safe replacement
You can replace object.ReferenceEquals(object, object) with the following extension method:
public static bool RefEquals<T>(this T? self, T? other) where T : class
{
return object.ReferenceEquals(self, other);
}
- Because of the
where T : classconstraint, you cannot invoke the extension method on structs. - Because both parameters are of the same type
T, the compiler has to find a singleTthat fits both arguments. If you give the extension method objects of two unrelated classes, no suchTexists, so the invocation does not compile.
Of course, nothing is foolproof: if one of the two arguments is of type object, then T becomes object, and the invocation compiles.
Unfortunately, the extension method rejects some invocations that are legitimate. If you compare an object of some class with an object of some interface which that class does not implement, the invocation does not compile, even though a subclass of that class might implement the interface, in which case the two references could point to the same object.
In such a case, you can explicitly indicate your assumption that the object referenced by the interface is an instance of the class, by casting it to the class. Then, both arguments are of the same class, and the invocation compiles:
Shape shape = GetShape(); // Shape does not implement IDrawable.
// A subclass of Shape might implement IDrawable.
IDrawable drawableShape = GetDrawableShape();
if (shape.RefEquals(drawableShape)) // does not compile
if (shape.RefEquals((Shape)drawableShape)) // compiles
Banning the original
Once you have the RefEquals() extension method, you will want to make sure that nobody invokes the original object.ReferenceEquals(object, object) by mistake. The banned API analyzers (GitHub, NuGet) let you do that. You list, in a file called BannedSymbols.txt, the symbols that must not be used, along with a message for each:
M:System.Object.ReferenceEquals(System.Object,System.Object) ; Use extension method `object.RefEquals(object)` instead, which only works for classes and is undefined for structs.
Then, every invocation of a listed symbol is reported with warning RS0030 "Do not use banned APIs".
However, the extension method itself has to invoke the original object.ReferenceEquals(object, object), so now the extension method gets warning RS0030. The extension method is the one place where invoking the original is legitimate, so you suppress RS0030 for that one invocation only:
public static bool RefEquals<T>(this T? self, T? other) where T : class
{
#pragma warning disable RS0030 // Do not use banned APIs
return object.ReferenceEquals(self, other);
#pragma warning restore RS0030 // Do not use banned APIs
}
object.Equals(object)
Consider a typical value type:
public readonly struct Point(int x, int y) : IEquatable<Point>
{
public int X { get; } = x;
public int Y { get; } = y;
public bool Equals(Point other) => X == other.X && Y == other.Y;
public override bool Equals(object? other) => other is Point kin && Equals(kin);
public override int GetHashCode() => HashCode.Combine(X, Y);
}
Whenever you implement IEquatable<T>, you are supposed to also override Equals(object) (code analysis rule CA1067 insists on it), so that code which only sees your object as an object, such as object.Equals(a, b) or the non-generic collections, compares it correctly.
However, since Equals(object) accepts anything, comparing two things that can never be equal compiles fine, and silently yields false:
Point point = new(3, 4);
if (point.Equals((3, 4))) // compiles, but is always false
The strongly typed Equals(Point) cannot accept a tuple, so the invocation goes to Equals(object), and the mistake goes unnoticed.
Banning it
The banned API analyzers can catch this mistake. If you add the override to BannedSymbols.txt, like this:
M:Point.Equals(System.Object) ; Use Equals(Point) instead.
then point.Equals((3, 4)) is reported with warning RS0030, while invocations of Equals(object) on a variable of type object are not reported, so the code which only sees a Point as an object keeps working without warnings.
Marking it as obsolete
Another way to discourage invocations of the Equals(object) method of your value types is to mark that method as obsolete, as follows:
[Obsolete("Use Equals(Point) instead.")]
public override bool Equals(object? other) => other is Point kin && Equals(kin);
Now, if you do this, you will notice two problems:
- The compiler issues CS0809 "obsolete method overrides non-obsolete method" on the declaration of your
Equals()override. What you need to do is to suppress this warning. - Accidental invocations of the override are not flagged with obsoletion warnings by the compiler. That's okay; Visual Studio renders such invocation with the styling for obsolete members, so the mistake is visible.
For more about these mishaps, see CS0809: Obsolete member overrides non-obsolete member.
So, compared with banning, marking as obsolete is weaker, because you get no warning, only a visual cue. However, it has its advantages:
- It works without the banned API analyzers, which not everyone uses.
- It is written on the override itself, as close as possible to the code it applies to. With the banned API analyzers, you have to add a line to
BannedSymbols.txt, which is far apart. - With the banned API analyzers, you have to add a line for every type that overrides
Equals(object), so the file can get quite large. - The obsoletion goes wherever the type goes. Every project that uses
Pointsees the attribute, whereas aBannedSymbols.txtfile only affects the projects that are making use of banned API analyzers. (Yeah, some folks just don't use BannedApiAnalyzers. I don't know why, I presume they have religious objections to it.)
Comments are disabled until you accept functional cookies.