in

Microsoft Philippines Community

A community for users, customers, and partners of Microsoft products in the Philippines :)

Trivia #5

Last post 12-17-2006 10:28 PM by bonskijr. 10 replies.
Page 1 of 1 (11 items)
Sort Posts: Previous Next
  • 12-15-2006 11:11 AM

    Trivia #5

    What's wrong with the code below:

    public class MyClass

    {

        private int _id = 0;

        public int Id

        {

            get { return _id; }

            set { _id = value; }

        }

     

        public MyClass(int id)

        {

            _id = id;

        }

     

        public override bool Equals(object obj)

        {

            MyClass myClass = obj as MyClass;

            if (myClass == null)

            {

                return false;

            }

            return _id == myClass._id;

        }

     

        public override int GetHashCode()

        {

            return _id.GetHashCode();

        }

     

        public static bool operator==(MyClass left, MyClass right)

        {

            return left.Equals(right);

        }

     

        public static bool operator !=(MyClass left, MyClass right)

        {

            return !left.Equals(right);

        }

    }


     

    Filed under:
  • 12-15-2006 11:26 AM In reply to

    • amilr
    • Top 500 Contributor
      Male
    • Joined on 11-18-2003
    • Manila
    • Posts 50
    • Points 502

    Re: Trivia #5

    Your operator overloads do not handle nulls on the left side?
  • 12-15-2006 11:32 AM In reply to

    Re: Trivia #5

    it will cause infinite loop? Surprise
    Rodel E. Dagumampan
    Software Innovator, Technology Evangelist, Aspiring Entrepreneur, Farmer, Runner, Risk-Taker
  • 12-15-2006 12:21 PM In reply to

    • LaTtEX
    • Top 25 Contributor
    • Joined on 02-02-2005
    • Bonifacio Global City
    • Posts 2,164
    • Points 22,082
    • MVP

    Re: Trivia #5

    suddenserenity:
    it will cause infinite loop? Surprise

    Ditto. 

    Jon Limjap

    I-NAV Travel & ToursDotNET @ Kape Ni LaTtEXAng Kape Ni LaTtEX

  • 12-15-2006 12:27 PM In reply to

    • cruizer
    • Top 10 Contributor
      Male
    • Joined on 07-20-2004
    • Singapore
    • Posts 9,417
    • Points 65,306
    • MVP

    Re: Trivia #5

    so what's the way to avoid this problem?
    http://devpinoy.org/blogs/cruizer

    Naglalayong buksan at palayain ang kamalayan ng Pinoy .NET developer
  • 12-15-2006 1:24 PM In reply to

    • amilr
    • Top 500 Contributor
      Male
    • Joined on 11-18-2003
    • Manila
    • Posts 50
    • Points 502

    Re: Trivia #5

    Yeah rodel, you're right! That's the more common error. NullException will only occur if the left hand side is null, which is less common.

    cruizer:
    so what's the way to avoid this problem?

    Maybe just don't override == and != for non-value types.

  • 12-17-2006 11:25 AM In reply to

    Re: Trivia #5

    this is a bit tricky  than what you guys think.  Here are three failing test cases which expects a StackOverflowException:

       

    [Test, ExpectedException(typeof(StackOverflowException))]

    public void TwoInstancesAreNotNull()

    {

        MyClass myClass1 = new MyClass(1);

        MyClass myClass2 = new MyClass(2);

        bool equal = myClass1 == myClass2;

    }

     

    [Test, ExpectedException(typeof(StackOverflowException))]

    public void LeftInstanceIsNull()

    {

        MyClass myClass = new MyClass(1);

        bool equal = null == myClass;

    }

     

    [Test, ExpectedException(typeof(StackOverflowException))]

    public void RightInstanceIsNull()

    {

        MyClass myClass = new MyClass(1);

        bool equal = myClass == null;

    }

     

    They all raise NullReferenceException whether it does not involve null or null is at the left or at the right of the operator.

    Anyway, although i've seen suggestions to not override equality operators and use Equals override instead, they are there for convenience and for readability (imo).  There's just something wrong with my code which is the basics for overriding Equals and equality operators, anyone? 

  • 12-17-2006 2:03 PM In reply to

    Re: Trivia #5

    joeycalisay:

    this is a bit tricky  than what you guys think.  Here are three failing test cases which expects a StackOverflowException:

       

    [Test, ExpectedException(typeof(StackOverflowException))]

    public void TwoInstancesAreNotNull()

    {

        MyClass myClass1 = new MyClass(1);

        MyClass myClass2 = new MyClass(2);

        bool equal = myClass1 == myClass2;

    }

     

    [Test, ExpectedException(typeof(StackOverflowException))]

    public void LeftInstanceIsNull()

    {

        MyClass myClass = new MyClass(1);

        bool equal = null == myClass;

    }

     

    [Test, ExpectedException(typeof(StackOverflowException))]

    public void RightInstanceIsNull()

    {

        MyClass myClass = new MyClass(1);

        bool equal = myClass == null;

    }

     

    They all raise NullReferenceException whether it does not involve null or null is at the left or at the right of the operator.

    Anyway, although i've seen suggestions to not override equality operators and use Equals override instead, they are there for convenience and for readability (imo).  There's just something wrong with my code which is the basics for overriding Equals and equality operators, anyone? 

     

        public override bool Equals(object obj)

        {

            MyClass myClass = obj as MyClass;

            if (myClass == null)

            {

                return false;

            }

            return _id == myClass._id;

        }

     


    This the code that might cause the infinite loop as the overriden operator will be recursively called. You have to use ReferenceEquals i think. ;)

    Rodel E. Dagumampan
    Software Innovator, Technology Evangelist, Aspiring Entrepreneur, Farmer, Runner, Risk-Taker
  • 12-17-2006 2:47 PM In reply to

    • amilr
    • Top 500 Contributor
      Male
    • Joined on 11-18-2003
    • Manila
    • Posts 50
    • Points 502

    Re: Trivia #5

    joeycalisay:

    They all raise NullReferenceException whether it does not involve null or null is at the left or at the right of the operator.

    Anyway, although i've seen suggestions to not override equality operators and use Equals override instead, they are there for convenience and for readability (imo).  There's just something wrong with my code which is the basics for overriding Equals and equality operators, anyone? 

    Yeah upon closer inspection it does seem that a NullReferenceException will occur first before the StackOverFlow exception. This is because after some back and forth between == and Equals(), a null value will eventually be assigned to the left operand.

    Take the case of your first test case:

        MyClass myClass1 = new MyClass(1);

        MyClass myClass2 = new MyClass(2);

        bool equal = myClass1 == myClass2;

     

    1) call to ==: left = myClass1, right = myClass2

    2) call to Equals(): obj = myclass2

    3) call to ==: left = myClass2 , right = null

    4) call to Equals(): obj = null

    5) call to ==: left = null, right = null  ----> exception!


  • 12-17-2006 6:12 PM In reply to

    Re: Trivia #5

    suddenserenity:

    This the code that might cause the infinite loop as the overriden operator will be recursively called. You have to use ReferenceEquals i think. ;)

    no infinite loop pre since a nullref will result first as pointed out.  use referenceequals how?

  • 12-17-2006 10:28 PM In reply to

    • bonskijr
    • Top 50 Contributor
      Male
    • Joined on 09-01-2004
    • Repatriated
    • Posts 873
    • Points 8,646

    Re: Trivia #5

    joeycalisay:

    What's wrong with the code below:

    public class MyClass

    {

        private int _id = 0;

        public int Id

        {

            get { return _id; }

            set { _id = value; }

        }

     

        public MyClass(int id)

        {

            _id = id;

        }

     

        public override bool Equals(object obj)

        {

            MyClass myClass = obj as MyClass;

            if (myClass == null)

            {

                return false;

            }

            return _id == myClass._id;

        }

     

        public override int GetHashCode()

        {

            return _id.GetHashCode();

        }

     

        public static bool operator==(MyClass left, MyClass right)

        {

            return left.Equals(right);

        }

     

        public static bool operator !=(MyClass left, MyClass right)

        {

            return !left.Equals(right);

        }

    }

        public static bool operator==(MyClass left, MyClass right)

        {

                if ((object) left == null || (object)right == null) return false; // handle also the checking of nulls in the overriden operator

                return left.Equals(right);

        }

     

        public static bool operator !=(MyClass left, MyClass right)

        {

                return !(left == right)   // negate the result

        }

     

    Have to explicitly check null on either side when overriding the == operator; although you're letting the Equals method handle the equality of the both sides the Equals method itself uses the == operator. However as amilr pointed the sooner the == operation is used by Equals it doesn't have a check for nulls on either side that's why there's NullRefernceException being thrown.

    hth 

     

    Bonski's Box | Buhay Saudi
Page 1 of 1 (11 items)
Copyright © 2008 Microsoft Philippines Community

Powered by Community Server (Commercial Edition), by Telligent Systems