Is code that uses the static Object.Equals to check for null more robust than code that uses the == operator or regular Object.Equals? Aren\'t the latter two vulnerable to b
When you want to test IDENTITY (same location in memory):
ReferenceEquals(a, b)
Handles nulls. And is not overridable. 100% safe.
But make sure you really do want IDENTITY test. Consider the following:
ReferenceEquals(new String("abc"), new String("abc"))
which returns false. In contrast:
Object.Equals(new String("abc"), new String("abc"))
and
(new String("abc")) == (new String("abc"))
both return true.
If you are expecting an answer of true in this situation, then you want an EQUALITY test, not an IDENTITY test.
See the next part.
When you want to test EQUALITY (same contents):
Use "a == b" if the compiler doesn't complain.
If that is rejected (if the type of variable a does not define "==" operator), then use "Object.Equals(a, b)".
IF you are inside of logic where a is known to not be null, THEN you may use the more readable "a.Equals(b)". For example, "this.Equals(b)" is safe. Or if "a" is a field that is initialized at construction time, and the constructor throws exception if null is passed in as the value to be used in that field.
NOW, to address the original question:
Q: Are these susceptible to being overridden in some class, with code that does not handle null correctly, resulting in an exception?
A: Yes. The only way to get 100% safe EQUALITY test would be to pre-test for nulls yourself.
But should you? The bug would be in that (hypothetical future bad class), and it would be a straightforward type of failure. Easy to debug and fix (by whoever supplies the class). I doubt it is a problem that happens often, or persists long when it does happen.
More detailed A: Object.Equals(a, b) is most likely to work in the face of a poorly written class. If "a" is null, the Object class will handle it itself, so no risk there. If "b" is null, then the DYNAMIC (run-time not compile-time) type of "a" determines what "Equals" method gets called. The called method merely has to work correctly when "b" is null. Unless the called method is extremely poorly written, the first step it does is determine whether "b" is a type that it understands.
So Object.Equals(a, b) is a reasonable compromise between readability/coding_effort and safety.