|
-
Feb 21st, 2009, 02:19 PM
#1
Thread Starter
Frenzied Member
[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 ==?
-
Feb 23rd, 2009, 06:21 AM
#2
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|