C# Type Comparison: Type.Equals vs operator ==

I posted a question on StackOverflow on why R# is suggesting the use of operater == over Type.Equals. The initial upvoted response said they two are equivalent and == is more readable.

Whenver R# has suggested a change, there is usually a valid reason/explanation. In this case, why is R# suggesting the use of operator == over Type.Equals for Type Comparison?

For reference, here is the StackOverflow question:
http://stackoverflow.com/questions/9234009/c-sharp-type-comparison-type-equals-vs-operator

Thanks!

0
2 comments
Avatar
Permanently deleted user

Generally, for reference types, == compares object references whereas Equals compares values. Because .NET always returns references to the same Type instance for a given class then == and Equals are the same for Type objects.

I would imagine the suggestion is therefore for these reasons:
- They are functionally equivalent
- Choosing one or the other and always using that one makes code consistent.
- As the StackOverflow poster mentions, == can be considered more readable (certainly for people with a C / C++ background).
- Generally the Equals method needs to be overloaded to provide useful behaviour and that has not been done in this case so using it is deceptive (it suggests more is going on than actually is). The == could be overridden also but that's less likely.
- There's quite a bit of confusion around == and Equals so it's good to use the simple one when it gives you the right answer.

There may be other reasons but they're the ones i can think of off the top of my head :)

Cheers,
Chris

0
Avatar
Permanently deleted user

I invite you to read the answer I just posted to your StackOverflow post: http://stackoverflow.com/a/9259279/183367
Basically, Equals() checks for underlying runtime types and == checks for the Type itself.

0

Please sign in to leave a comment.