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.
The suggested answer is not complete,
IEquatable.Equals() method has to return TRUE if objects are equal
Wrong answer! Not all code paths return a value.
if(other==null) return false;
if(this.Id != other.Id) return false
return true;
class Class1:IEquatable
{
public Int32 ID { get; set; }
public String Name { get; set; }
public bool Equals(Class1 other)
{
if (other == null)
{
return false;
}
if (this.ID != other.ID)
{
return false;
}
if (!Object.Equals(this.Name,other.Name))
{
return false;
}
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;
correct!
CORRECT
What is the difference
between
if (!Object.Equals(this.Name,other.Name))
and
if (!this.Name.Equals(other.Name)).
If this.Name is null, calling .Equals() on it will result in a NullReferenceException.
Object.Equals (obj, obj) compares the REFERENCE (true if they point to same object). Two strings, even having the same value will never have the same reference. So it is not applicable here.
My solution:
if (other == null) return false;
if (this.ID != other.ID) return false;
if (!this.Name.Equals(other.Name)) return false; //to use String class’ proper comparer
return true;
Correct.
NO!
Quoting MSDN:
For example, the value of a String object is based on the characters of the string; the String.Equals(Object) method overrides the Object.Equals(Object) method to return true for any two string instances that contain the same characters in the same order.
if (other == null)return false;
if (this.ID != other.ID)return false;
if (!Object.Equals(this.Name,other.Name))return false;
return true;
IS CORRECT ANSWER.
TESTED!!!
Object.Equals(this.Name, other.Name) only returns true if the strings represented by Name in both objects point to the same string (not necessarily the same text)
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
CORRECT