DRAG DROP
You have the following class:
You need to implement IEquatable. The Equals method must return true if both ID and Name are set
to the identical values. Otherwise, the method must return false. Equals must not throw an
exception.
What should you do? (Develop the solution by selecting and ordering the required code snippets.
You may not need all of the code snippets.)
Answer: See the explanation
correct, but incomplete.
The last instruction would be:
return true;
if (other == null)return false;
if (this.ID != other.ID)return false;
if (!Object.Equals(this.Name,other.Name))return false;
return true;
Should be “if (!Object.Equals(this.Name,other.Name))return false;” because as MSDN says (https://msdn.microsoft.com/en-us/library/w4hkze5k(v=vs.110).aspx): firstly checked objects represent same object reference, secondly it determines whether either objA or objB is null, and finally it calls objA.Equals(objB) and returns the result
Why is ‘if (!this.Name.Equals(other.Name))’ not sufficient in this case ?
I don’t understand the expression ‘if (!Object.Equals(this.Name,other.Name))return false;’ here.
‘Object.Equals()’ offers referential equality, which is not necessary here
as you can see above : ” .. true if both ID and Name are set to the identical values .. “
what if this.Name is null, then you will get a exception…
‘Object.Equals(this.Name,other.Name)’ replies TRUE, if both values are ‘null’
@see https://msdn.microsoft.com/en-us/library/w4hkze5k(v=vs.110)
.. in contrast : ‘Name.Equals(other.Name)’ does not !
@see https://msdn.microsoft.com/en-us/library/858x0yyx(v=vs.110).aspx