Why does the C# compiler not even complain with a warning on this code? :
if (this == null)
{
// ...
}
Obviously the condition will never be satisfied..
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because you could override
operator ==to return true for that case.Running
new Foo().Test()will print “True” to the console.The other question here is: why doesn’t the compiler issue a warning for
ReferenceEquals(this, null)? From the bottom of the above link:That might be answered by @Aaronaught’s response. And that’s also why you should be doing
(object)x == nullorReferenceEquals(x, null), not doing a simplex == null, when you’re checking for null references. Unless, of course, you’re sure that the==operator is not overloaded.