简体   繁体   中英

Implement Method of Object Class => public virtual bool Equals(obj);

We Have to implement the method of object class => public virtual bool Equals(obj); without using Equals or Reference Equals Method. It has to work same as virtual Equals Method.

I can use objA == objB .

I won't give you a code answer, since this is an assignment after all.

Things you want to check:

  1. Null - are both objects null? Is one object null and the other isn't?

    object.ReferenceEquals(objA, null) is the old preferable way (since it doesn't potentially use an overriden Equals implementation as == would. With C# 7+, you can also use if (objA is null) .

  2. You can now compare if (objA == objB) . Note that it's here where objA.Equals(objB) would be used, but since that's not allowed, I guess we can use == .

There is also objA.GetHashCode() which indicates the potential for equality. I say "potential" because it's possible for two very different objects to have the same hash code. If two objects are equal (and correctly implemented) then they should have the same hash code. In short: you can rely on GetHashCode() to indicate the possibility of equality, but you need to do another check (2) to be sure.

See here for more on the relationship between GetHashCode() and Equals() . And see here for more information about == vs Equals()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM