PrepAway - Latest Free Exam Questions & Answers

You need to implement IEquatable

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.)

PrepAway - Latest Free Exam Questions & Answers

Answer: See the explanation.

Explanation:
Box 1:

Box 2:

Box 3:

17 Comments on “You need to implement IEquatable

  1. theAllKnowingGuy says:

    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;
    }
    }




    2



    0
  2. Andre Aranha says:

    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;




    0



    0
    1. anarius says:

      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.




      1



      0
  3. Rao says:

    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!!!




    0



    0
    1. Ronald Mariah says:

      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)




      0



      0
  4. Manab says:

    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




    0



    0

Leave a Reply