Using overloaded operator== in a generic function

Posted by Dimitri C. on Stack Overflow See other posts from Stack Overflow or by Dimitri C.
Published on 2010-05-27T07:28:06Z Indexed on 2010/05/27 7:31 UTC
Read the original article Hit count: 146

Filed under:
|

Consider the following code:

class CustomClass
{
    public CustomClass(string value)
        { m_value = value; }

    public static bool operator==(CustomClass a, CustomClass b)
        { return a.m_value == b.m_value; }

    public static bool operator!=(CustomClass a, CustomClass b)
        { return a.m_value != b.m_value; }

    public override bool Equals(object o)
        { return m_value == (o as CustomClass).m_value; }

    public override int GetHashCode()
        { return 0; /* not needed */ }

    string m_value;
}

class G
{
    public static bool enericFunction1<T>(T a1, T a2) where T : class
        { return a1.Equals(a2); }
    public static bool enericFunction2<T>(T a1, T a2) where T : class
        { return a1==a2; }
}

Now when I call both generic functions, one succeeds and one fails:

var a = new CustomClass("same value");
var b = new CustomClass("same value");
Debug.Assert(G.enericFunction1(a, b)); // Succeeds
Debug.Assert(G.enericFunction2(a, b)); // Fails

Apparently, G.enericFunction2 executes the default operator== implementation instead of my override. Can anybody explain why this happens?

© Stack Overflow or respective owner

Related posts about c#

Related posts about generics