Define operator == and !=

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

Hello!

If I define operator == and != is then nessesary to override method Equals
and GetHashCode that is inherited from
System.Object ?

If yes will Equals have the same functionalitty as operator == ?

So can I then just restrict the functionality to one method and just call
this method from the other ?

Does this sound correct ?

//Tony
 
Tony Johansson said:
If I define operator == and != is then nessesary to override method Equals
and GetHashCode that is inherited from
System.Object ?

It's at least a very good idea to do so.
If yes will Equals have the same functionalitty as operator == ?

Again, it's a very good idea to make Equals and == do the same thing.
So can I then just restrict the functionality to one method and just call
this method from the other ?

Does this sound correct ?

Yes.
 
Tony Johansson said:
Hello!

If I define operator == and != is then nessesary to override method Equals
and GetHashCode that is inherited from
System.Object ?

If yes will Equals have the same functionalitty as operator == ?

So can I then just restrict the functionality to one method and just call
this method from the other ?

Does this sound correct ?

//Tony

They are not strictly identical, as operator== might be called with two null
references, whereas this cannot arise when you are overriding object's
virtual Equals method.

If using VS2005, overriding GetHashCode is very simple - when you type
"public override" the intellisense suggests things you can override - if you
click GetHashCode it writes the whole function for you, calling
"base.GetHashCode()". You only need to rewrite the code in it if your
redefinition of equality causes two objects that are "equal" give different
hash codes.
 
If using VS2005, overriding GetHashCode is very simple - when you type
"public override" the intellisense suggests things you can override - if you
click GetHashCode it writes the whole function for you, calling
"base.GetHashCode()". You only need to rewrite the code in it if your
redefinition of equality causes two objects that are "equal" give different
hash codes.

On the other hand, that's true of all of ==, !=, Equals and
GetHashCode.

If the default implementation isn't appropriate for one of them,
chances are it won't be appropriate for any of them - at least for
reference types.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top