Skip to main content
gamedev.net
🔒 Locked

[.net] C# custom operator == problem

Started by Dope-Show Apr 25, 2006 at 9:10 AM 1 replies 1.7k views
Original Post
Dope-Show
Dope-Show
I have a class

class Test
{
    float a;

    public static bool operator ==(Test t1, Test t2)
    {
        if (t1 == null)
            return t2 == null;

        return t1.Equals(t2);
    }

    public static bool operator !=(Test t1, Test t2)
    {
        if (t1 == null)
            return t2 != null;

        return !t1.Equals(t2);
    }

    public override bool Equals(object obj)
    {
        Test t = obj as Test;

        if(t == null)
            return false;

        return this.a == t.a;
    }
}

and some code that tests is

Test t = new Test();
bool b = t == null;

My problem is, that when the t == null is executed the operator == is invoked, which is fine, but inside the operator I test for null again, which invokes the operator again, resulting in an infinite loop. I wonder why this isn't working, while the == operator in the System.Delegate class works the same way, and it works there

public static bool operator ==(Delegate d1, Delegate d2)
{
      if (d1 == null)
      {
            return (d2 == null);
      }
      return d1.Equals(d2);
}

Sorry for my bad english.
Arild Fines
Arild Fines
No idea why this works in Delegate, but you can implement your operator== like this:

        public static bool operator ==( Test t1, Test t2 )        {            if ( Object.ReferenceEquals(t1, null ))                return Object.ReferenceEquals(t2, null);            return t1.Equals( t2 );        }


Quote:
Original post by Dope-Show
Sorry for my bad english.

Eh?
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]
Dope-Show
Dope-Show
Thanks for the reply. I thought about using ReferenceEquals, too, but since it works for the Delegate class and the other Standard Library classes i thought it would be more elegant to use the operator.


Quote:
Original post by Arild Fines
Quote:
Original post by Dope-Show
Sorry for my bad english.

Eh?


Well, I don't consider my english as good english, for I am not an native speaker. And I don't know if a language learnt mostly by playing english computer and video games plus some english learnt in school (actually 9 years) can be considered as good. I still have problems with commas.
But I think compared to other non-native speakers, especially the german ones, my english can be considered as good [cool][grin][grin][grin][grin]

P.S.: The last sentence was meant ironically [wink]

Quote:

Homer: "So, Mr. Malloy, it seems that the cat has been caught by the very
person who was trying to catch him."

Principal Skinner: "How ironic."

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.