Results 1 to 2 of 2

Thread: [2.0] Implement ==?

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2005
    Posts
    1,547

    [2.0] Implement ==?

    Code:
    class test
            {
                public int i = 0;
                static  bool EqualsHelper(test a, test b)
                {
                    return (a.i == b.i);
                }
                static bool Equals(test a, test b)
                {
                    return ((a == b) || (((a != null) && (b != null)) && EqualsHelper(a, b)));
                }
                public static bool operator !=(test a, test b)
                {
                    return !Equals(a, b);
                }
                public static bool operator ==(test a, test b)
                {
                    return Equals(a, b);
                }
                public test(int a)
                {
                    i = a;
                }
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                if (new test(1) != null)
                {
                    if (new test(1) == new test(1))
                    {
    
                    }
                }
            }
    I keep getting a stack overflow, yet this is how System.String is setup.

    How do you correctly implement ==?

  2. #2
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: [2.0] Implement ==?

    .Equals is reference equality.
    == is value equality

    Because they mean different things, you can't or rather shouldn't use == to call Equals() on the objects themselves, but on values of properties in the objects.

    I see that in the ==, you're calling Equals, which then does a==b, which in turn will call Equals. That's why you're getting the stack overflow.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width